在这里,我们将看到如何使用不同的线程按正确的顺序打印数字。在这里,我们将创建n个线程,然后对它们进行同步。思路是,第一个线程将打印1,然后第二个线程将打印2,依此类推。当一个线程尝试打印时,它将锁定资源,因此其他线程无法使用该部分。
示例
#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
输出
$ g++ test.cpp -lpthread$ ./a.outEnter number of threads: 51 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 34 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 51 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 34 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 12 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 45 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 23 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5.........登录后复制
以上就是使用线程同步打印数字的顺序的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2580639.html