热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

开发笔记:一个线程多次调用一个函数

篇首语:本文由编程笔记#小编为大家整理,主要介绍了一个线程多次调用一个函数相关的知识,希望对你有一定的参考价值。

篇首语:本文由编程笔记#小编为大家整理,主要介绍了一个线程多次调用一个函数相关的知识,希望对你有一定的参考价值。



说有这个整数A。每次func()运行时,将A增加1.并且我用2个线程调用此函数。示例:如果用户给出输入5,则每个线程运行5次,这使得A = 10

这就是我在主线程中所拥有的:

for ( i = 0; i <5; i++)
{
pthread_create(&thread1, NULL, (void*)func, (void*)args);
pthread_create(&thread2, NULL, (void*)func, (void*)args2);
}
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);

我的方式是,如果用户希望每个线程运行5次。我将创建一个循环,每次创建“新”线程,这实际上是覆盖。我想我们可以说我打了10个线程,或者我使用了pthread_create() 10次。

但我被告知这是错的。应该是我只创建了2个线程,每个线程运行5次。但后来我不明白,我怎么能用每个线程调用该函数5次。如果我想要一个函数,我每次都必须使用pthread_create(),对吧?

无论如何,如果没有循环pthread_create() 5次,我仍然可以用线程调用func() 5次?


答案

不,你不可能多次运行one run thread,因为for n number of thread creation, you have to declare that many no of threads和线程共享它们运行的​​进程的地址空间,并且一旦使用pthread_join()收集返回状态,就有自己的堆栈来运行线程函数,thread_1是完成后,再也无法运行了。 thread1

因此,只有解决方案是创建5个pthread_t变量或创建array of pthread_t

解决方案-1:

int main()
{
pthread_t thread1,thread2,thread3,thread4,thread5;
pthread_create(&thread1, NULL, (void*)func1, (void*)args1);
pthread_create(&thread2, NULL, (void*)func2, (void*)args2);
pthread_create(&thread3, NULL, (void*)func3, (void*)args3);
pthread_create(&thread4, NULL, (void*)func4, (void*)args4);
pthread_create(&thread5, NULL, (void*)func5, (void*)args5);
//and that many times you should use pthread_join() to avoid undefined behaviour
/*If multiple threads simultaneously try to join with the same thread, the results are undefined. If the thread calling pthread_join() is cancelled,
then the target thread will remain joinable*/
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
...
pthread_join(thread5, NULL);
}

解决方案2:

pthread_t thread_var[5];
for(i=0 ;i<5 ;i++) {
pthread_create(&thread_var[i],NULL,/** call through fun-ptr**/,(void*)args);
}

正如其他人所指出的那样由于你只为5个线程定义了一个处理程序func,所有线程都在访问same thread handler(func),它可能会在unexpected result中产生,因为所有线程都试图在access/modify中使用func相同的变量。

无论如何,如果没有循环pthread_create()5次,我仍然可以使用线程调用func()5次?

我认为意图可能是不要将func() from main thread称为5次,这是不可能的,而不是运行main thread only oncefunc()你可以使用thread_handler在不同的mutex之间切换。

pthread_mutex_t m1,m2,m3;
void* fun1(void *p)
{
pthread_mutex_lock(&m1);
/** do ssome task here**/
sleep(1);
pthread_mutex_unlock(&m2);
}
void* fun2(void *p)
{
pthread_mutex_lock(&m2);
/** do some task here **/
sleep(1);
pthread_mutex_unlock(&m3);
}
void* fun3(void *p)
{
pthread_mutex_lock(&m3);
/*** do some task here **/
sleep(1);
pthread_mutex_unlock(&m1);
}


推荐阅读
author-avatar
CK92_474
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有