c - 我想在 C 中并行编程,我应该避免使用 pthread_join() 吗?

标签 c multithreading pthreads sequential

我想创建多个线程并在创建它们的同时启动它,以使代码尽可能快地运行 我试着这样做:

for (i = 1; i < nbClients+1; i++)
{
    pthread_create(&tClient, NULL, procedureClient, &i);
    pthread_join(tClient, NULL);

    free(clients[i].panier); //Libération de la mémoire pour chaque panier
}

如果我执行 pthread_join,主线程将暂停,因此它是顺序的,所以如果我这样做:

for (i = 1; i < nbClients+1; i++)
{
    pthread_create(&tClient, NULL, procedureClient, &i);

    free(clients[i].panier); //Libération de la mémoire pour chaque panier
}

这个执行是并行的吗?如果我的 printf 出现问题是否正常? (我认为这是正常的,但我更想问)

谢谢

最佳答案

存在以下问题。

  1. 您需要为不同的线程设置不同的 pthread_t 句柄。
  2. 不同的线程需要不同的 arg 变量。
  3. 您应该在创建所有线程后调用 pthread_join()。 pthread_join()将阻塞调用线程,直到另一个线程退出。这将等待该线程退出。

.

pthread_t tClient[MAX_NUM_THREADS];
int       arg[MAX_NUM_THREADS] = {0};

for (i = 0; i < nbClients; i++)
{
    arg[i] = i+1; //Changed your for loop.
    pthread_create(&(tClient[i]), NULL, procedureClient, (void*)&(arg[i]));
}

/* Other code. */

for (i = 0; i < nbClients; i++)
{
    pthread_join(tClient[i], NULL); //Will wait for ith thread to exit.

    free(clients[i].panier); //Libération de la mémoire pour chaque panier
}

is this execution parallel ? is it normal if my printf are in a disorder ? (i think that this is normal but i prefer to ask)

现在执行是并行的。 不同线程中的打印可能会以不同的顺序出现。这取决于在什么时间安排哪个线程。 您可以使用互斥量、信号量、条件变量来同步线程。等等

关于c - 我想在 C 中并行编程,我应该避免使用 pthread_join() 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40830228/

相关文章:

python - 如何知道 Python multiprocessing.Lock 是否被释放?

.net - 基于多线程的应用程序的哪种类型的设计图?

c++ - Pthreads 在互斥锁中间死亡

c - 了解 C malloc 和 sbrk()

c - 使用常量时报错: too few arguments in function call,

java - 尝试将线程与 JProgressBar 一起使用

c - pthread_cond_wait 不解锁互斥体

c - 程序不读取整个文件

c - while(*p){p++;}、while (*++p){;} 和 while(*p++){;} 有什么区别?

c - 如何使用用户输入创建全局变量