使用线程同步打印数字的顺序

2023年 9月 22日 40.9k 0

#include
#include
#include
#include
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("

Enter 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;
}

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论