【发布时间】:2015-11-19 02:49:57
【问题描述】:
例如,使用pthread_create创建两个线程,两个线程都打印“hello world”,我的问题是如何计算每个线程打印了多少次“hello world”?
【问题讨论】:
标签: c++ multithreading
例如,使用pthread_create创建两个线程,两个线程都打印“hello world”,我的问题是如何计算每个线程打印了多少次“hello world”?
【问题讨论】:
标签: c++ multithreading
我的问题是如何计算“hello world”打印了多少次 每个线程?
最简单的方法是在文件顶部声明一个全局原子计数器:
static std::atomic<int> counter = 0;
然后让每个线程在每次打印“hello world”时递增计数器(即 ++counter)。然后在你的 main() 中,所有线程都加入后,你可以打印出值计数器。
【讨论】:
我可以向你展示子线程将变量传递给主线程的代码;
void * thread_func(void *arg)
{
int num = 10; //assume 'num' is the times that child thread printed "hello world"
pthread_exit((void *)num);
}
int main()
{
pthread_t thread;
void * tret;
pthread_create(&thread,NULL,thread_func,NULL);
pthread_join(thread,&tret);
printf("%d\n",(int)tret);
return 0;
}
【讨论】:
num的类型有问题。num的类型应该是long,但是其他代码是正确的。你应该返回(void *)num ,不是(void *)&num。如果你返回(void *)&num,这将返回一个指向局部变量的porter。
std::intptr_t 或std::uintptr_t(但我相信它可以正常工作)。也可以只是return (void*)num; BTW / 使用pthread_exit 是可选的,如果您将 pthreads 移至例如,则需要额外的移植工作。 std::thread 等人。