如何通过引用pthread启动例程传递顺序计数器? [英] How to pass a sequential counter by reference to pthread start routine?
问题描述
下面是我的C代码,用于打印一个递增的全局计数器,每个线程一个增量.
Below is my C code to print an increasing global counter, one increment per thread.
#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?
示例输出:
线程:2 线程数:3 线程数:5 线程数:6 线程数:7 线程数:7 线程数:8 线程数:9 线数:10 线程:10
thread:2 thread:3 thread:5 thread:6 thread:7 thread:7 thread:8 thread:9 thread:10 thread:10
修改
蓝月亮的答案解决了这个问题. MartinJames的评论中提供了替代方法.
Blue Moon's answer solves this question. Alternative approach is available in MartinJames'es comment.
推荐答案
一种简单但无用的方法是确保thread1打印1
,thread2打印2
,以此类推将 join 立即线程:
A simple-but-useless approach is to ensure thread1 prints 1
, thread2 prints 2
and so on is to put join the thread immmediately:
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.
请注意,我删除了多余的强制类型转换,线程函数也接受了void *
参数.
Note that I removed the superfluous casts and also the thread function takes a void *
argument.
一种更明智的方法是按值传递循环计数器i
,以便每个线程将打印不同的值,并且您会看到线程正在运行,即编号1-10
可以按任何顺序打印,并且每个线程也会打印一个唯一值.
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 i.e. the numbers 1-10
could be printed in any order and also each thread would print a unique value.
这篇关于如何通过引用pthread启动例程传递顺序计数器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!