[英]How to pass a sequential counter by reference to pthread start routine?
Below is my C code to print an increasing global counter, one increment per thread. 下面是我的C代码,用于打印一个递增的全局计数器,每个线程一个增量。
#include <stdio.h>
#include <pthread.h>
static pthread_mutex_t pt_lock = PTHREAD_MUTEX_INITIALIZER;
int count = 0;
int *printnum(int *num) {
pthread_mutex_lock(&pt_lock);
printf("thread:%d ", *num);
pthread_mutex_unlock(&pt_lock);
return NULL;
}
int main() {
int i, *ret;
pthread_t pta[10];
for(i = 0; i < 10; i++) {
pthread_mutex_lock(&pt_lock);
count++;
pthread_mutex_unlock(&pt_lock);
pthread_create(&pta[i], NULL, (void *(*)(void *))printnum, &count);
}
for(i = 0; i < 10; i++) {
pthread_join(pta[i], (void **)&ret);
}
}
I want each thread to print one increment of the global counter but they miss increments and sometimes access same values of global counter from two threads. 我希望每个线程打印全局计数器的一个增量,但它们会错过增量,有时会从两个线程访问全局计数器的相同值。 How can I make threads access the global counter sequentially? 如何使线程顺序访问全局计数器?
Sample Output : 样本输出 :
thread:2 thread:3 thread:5 thread:6 thread:7 thread:7 thread:8 thread:9 thread:10 thread:10 螺纹:2螺纹:3螺纹:5螺纹:6螺纹:7螺纹:7螺纹:8螺纹:9螺纹:10螺纹:10
Edit 编辑
Blue Moon's answer solves this question. 蓝月亮的答案解决了这个问题。 Alternative approach is available in MartinJames'es comment. MartinJames的评论中提供了替代方法。
A simple-but-useless approach is to ensure thread1 prints 1
, thread2 prints 2
and so on is to put join the thread immmediately: 一种简单但无用的方法是确保thread1打印1
,thread2打印2
,以此类推立即将线程加入 :
pthread_create(&pta[i], NULL, printnum, &count);
pthread_join(pta[i], (void **)&ret);
But this totally defeats the purpose of multi-threading because only one can make any progress at a time. 但这完全破坏了多线程的目的,因为一次只能有任何进展。
Note that I removed the superfluous casts and also the thread function takes a void *
argument. 请注意,我删除了多余的强制类型转换,并且线程函数也带有void *
参数。
A saner approach would be to pass the loop counter i
by value so that each thread would print different value and you would see threading in action ie the numbers 1-10
could be printed in any order and also each thread would print a unique value. 一个更明智的方法是按值传递循环计数器i
,以便每个线程将打印不同的值,并且您会看到线程正在运行,即数字1-10
可以按任何顺序打印,并且每个线程将打印唯一的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.