Computer >> 컴퓨터 >  >> 프로그램 작성 >> C 프로그래밍

스레드 동기화를 사용하여 순서대로 숫자 인쇄

<시간/>

여기에서 다른 스레드를 사용하여 올바른 순서로 숫자를 인쇄하는 방법을 볼 것입니다. 여기에서 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("\nEnter number of threads: ");
      scanf("%d", &threads);
   // allocate memory to cond (conditional variable) thread id'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
...
...
...