gpt4 book ai didi

c - (C, pthreads) 让多个线程同步并一起继续

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

我有一个由多个线程组成的程序。这些线程必须在某个时刻同步,继续在一起,完成不同长度的工作,然后再次同步。

以下是我的意思的示例:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>

#define NUM_THREADS 10

void* thread(void* idp);

int threads_running = 0;
pthread_mutex_t* mutex;
pthread_cond_t* cond;

int main(int args, char **argv)
{
pthread_mutex_t mutex_var;
pthread_cond_t cond_var;

mutex = &mutex_var;
cond = &cond_var;

pthread_mutex_init(mutex, NULL);
pthread_cond_init(cond, NULL);

pthread_t threads[NUM_THREADS];

for (int i = 0; i < NUM_THREADS; i++)
{
printf("Creating Thread %d....\n", i);

int* id = malloc(sizeof(int));
*id = i;

if(0 != pthread_create(&threads[i], NULL, thread, (void *) id))
{
perror("Error while creating the threads");
exit(1);
}
}

for (int i = 0; i < NUM_THREADS; i++)
{
pthread_join(threads[i], NULL);
}

return 0;
}


void* thread(void* idp)
{
int* id = (int*) idp;

while (1)
{
sleep(*id+2); // Thread work

pthread_mutex_lock(mutex);
threads_running++;
pthread_mutex_unlock(mutex);
pthread_cond_broadcast(cond);

printf("Thread %d WAIT\n", *id);
fflush(stdout);

// Let threads synchronize

pthread_mutex_lock(mutex);
while(threads_running != NUM_THREADS)
{
pthread_cond_wait(cond, mutex);
}
pthread_mutex_unlock(mutex);

printf("Thread %d WAKEUP\n", *id);
fflush(stdout);

// and continue

pthread_mutex_lock(mutex);
threads_running--;
pthread_mutex_unlock(mutex);
}
}

发生的事情是,一些(通常是#9和其他一两个)到达Thread %d WAKEUP,但在其他线程可以唤醒之前threads_running是已经小于 NUM_THREADS

如何同步多个线程,以便它们一起继续?我在对变量的并行访问进行思考时遇到了一些麻烦。

最佳答案

几秒钟后我找到了答案:

  1. while(threads_running != NUM​​_THREADS) 更改为 while(threads_running != 0 &&threads_running != NUM​​_THREADS)

  2. threads_running--; 更改为 threads_running = 0;

现在一切正常了。

关于c - (C, pthreads) 让多个线程同步并一起继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44609174/

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