首頁  >  文章  >  後端開發  >  使用執行緒同步列印數字的順序

使用執行緒同步列印數字的順序

王林
王林轉載
2023-09-22 21:41:10995瀏覽

使用執行緒同步列印數字的順序

在這裡,我們將看到如何使用不同的執行緒以正確的順序列印數字。在這裡,我們將建立n個線程,然後對它們進行同步。想法是,第一個執行緒將列印1,然後第二個執行緒將列印2,依此類推。當一個執行緒嘗試列印時,它將鎖定資源,因此其他執行緒無法使用該部分。

範例

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t* cond = NULL;
int threads;
volatile int count = 0;
void* sync_thread(void* num) { //this function is used to synchronize the threads
   int thread_number = *(int*)num;
   while (1) {
      pthread_mutex_lock(&mutex); //lock the section
      if (thread_number != count) { //if the thread number is not same as count, put all thread
          except one into waiting state
         pthread_cond_wait(&cond[thread_number], &mutex);
      }
      printf("%d ", thread_number + 1); //print the thread number
         count = (count+1)%(threads);
      // notify the next thread
      pthread_cond_signal(&cond[count]);
      pthread_mutex_unlock(&mutex);
   }
   return NULL;
}
int main() {
   pthread_t* thread_id;
   volatile int i;
   int* thread_arr;
   printf("</p><p>Enter number of threads: ");
      scanf("%d", &threads);
   // allocate memory to cond (conditional variable) thread id&#39;s and array of size threads
   cond = (pthread_cond_t*)malloc(sizeof(pthread_cond_t) * threads);
   thread_id = (pthread_t*)malloc(sizeof(pthread_t) * threads);
   thread_arr = (int*)malloc(sizeof(int) * threads);
   for (i = 0; i < threads; i++) { //create threads
      thread_arr[i] = i;
      pthread_create(&thread_id[i], NULL, sync_thread, (void*)&thread_arr[i]);
   }
   // waiting for thread
   for (i = 0; i < threads; i++) {
      pthread_join(thread_id[i], NULL);
   }
   return 0;
}

輸出

$ g++ test.cpp -lpthread
$ ./a.out

Enter number of threads: 5
1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3
4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5
1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3
4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1
2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4
5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2
3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5
...
...
...

以上是使用執行緒同步列印數字的順序的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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