gpt4 book ai didi

c - 一个线程多次调用一个函数

转载 作者:行者123 更新时间:2023-11-30 19:31:50 25 4
gpt4 key购买 nike

假设有一个整数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次。我将创建一个循环,每次它都会创建"new"线程,这实际上是覆盖。我想我们可以说我调用了 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);
}

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

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

我认为意图可能是不调用func() from main thread 5 次这是不可能的,而是运行 main thread only once和来自 func()您可以在不同的 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);
}

关于c - 一个线程多次调用一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47850721/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com