首頁  >  文章  >  後端開發  >  使用C語言的線程無限打印1 2 3

使用C語言的線程無限打印1 2 3

WBOY
WBOY轉載
2023-08-29 08:17:021081瀏覽

使用C语言的线程无限打印1 2 3

在這裡,我們需要使用C程式語言中的執行緒無限次地重複列印1 2 3序列。

讓我們來看看我們程式碼的樣本輸出:

1 2 3 1 2 3 1 2 3 1 2 3

為此,我們將需要使用三個在C程式語言中並行運行的執行緒。還需要一個變量,在第一個線程中初始化為1,並根據其上一個值更新其值。然後在函數中運行一個無限循環。

範例

讓我們看看實作我們解決方案的程式:

#include <stdio.h>
#include <pthread.h>
pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond2 = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond3 = PTHREAD_COND_INITIALIZER;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
int value = 1;
void *foo(void *n){
   while(1) {
      pthread_mutex_lock(&lock);
      if (value != (int)*(int*)n) {
         if ((int)*(int*)n == 1) {
            pthread_cond_wait(&cond1, &lock);
         } else if ((int)*(int*)n == 2) {
            pthread_cond_wait(&cond2, &lock);
         } else {
            pthread_cond_wait(&cond3, &lock);
         }
      }
      printf("%d ", *(int*)n);
      if (value == 3) {
         value = 1;
         pthread_cond_signal(&cond1);
      }
      else if(value == 1) {
         value = 2;
         pthread_cond_signal(&cond2);
      } else if (value == 2) {
            value = 3;
            pthread_cond_signal(&cond3);
      }
      pthread_mutex_unlock(&lock);
   }
   return NULL;
}
int main(){
   pthread_t tid1, tid2, tid3;
   int n1 = 1, n2 = 2, n3 = 3;
   pthread_create(&tid1, NULL, foo, (void *)&n1);
   pthread_create(&tid2, NULL, foo, (void *)&n2);
   pthread_create(&tid3, NULL, foo, (void *)&n3);
   while(1);
   return 0;
}

輸出

1 2 3 1 2 3 1 2 3 1 2 3 1 2 3&hellip;.

以上是使用C語言的線程無限打印1 2 3的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除