C pthread_create 和 join 在 main 函数之外

标签 c multithreading pthreads

#include <stdio.h>
#include <stdlib.h>
#include <semaphore.h>
#include <pthread.h>

int ids = 0;
sem_t sync;
int idx = 0;
int count = 0;


void * add2(void * p_idx) {
    int * tmp = (int *) p_idx;
    int id = ids++;
    sem_wait(&sync);
    (*tmp)++;
    count++;
    printf("executed by %d, number is %d\n", id, *tmp);
    sem_post(&sync);
}

int createThreadOutsideMain() {
    pthread_t *outsideMain = malloc(sizeof(pthread_t));
    pthread_create(outsideMain, NULL, add2, (void *) &idx);
    pthread_join(*outsideMain, NULL);
    return 0;
}

void * add(void * p_idx) {
    int * tmp = (int *) p_idx;
    int id = ids++;
    while(count < 10) {
        if (count % 2 == 0) {
            continue;
        }
        sem_wait(&sync);
        (*tmp)++;
        count++;
        printf("executed by %d, number is %d\n", id, *tmp);
        sem_post(&sync);
    }
    createThreadOutsideMain();
}


int main(int argc, char * argv[]) {
    pthread_t insideMain1, insideMain2;
    sem_init(&sync, 0, 1);
    pthread_create(&insideMain1, NULL, add, (void *) &idx);
    pthread_create(&insideMain2, NULL, add, (void *) &idx);
    pthread_join(insideMain1, NULL);
    pthread_join(insideMain2, NULL);
    return 0;
}

我是 C 和 pthread 库的新手,我遇到了一个情况。一般描述如下。 我想创建线程并在运行时根据输入在main函数之外加入线程,所以这里我使用一个if语句来创建一个新的 如果 count 是奇数则线程。 我希望所有线程都使用相同的信号量 &sync,但是当我运行代码时,它就卡住了, 我想要这样的输出

由0执行,数量为0

由1执行,数量为1

由2执行,数量为2

由3执行,数量为3

执行者为0,数量为4

由4执行,数量为5

由2执行,数量为6

执行者为0,编号为7 ...

这个想法可行吗?如果是这样,我的问题出在哪里,感谢您的帮助!

最佳答案

首先修复下面的 while 循环,然后重试。该循环将无限期,因为 if 中的条件始终为 true。原因是,当您从第一个线程调用 add 方法时,您传递的参数为零。首先,它锁定互斥体并永远卡在 while 循环中,而您的第二个线程正在等待锁解锁。因此,您的应用程序最终永远陷入循环中。将参数传递为 1 并检查发生了什么。

  while(count < 10) {
    if (count % 2 == 0) {// value of (0 % 2) == 0 always and this loop will continue for ever
        continue;
    }

关于C pthread_create 和 join 在 main 函数之外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47243079/

相关文章:

c++ - 在 C/C++ 中将数组转换为矩阵?

java - 比较 Java 和 GPar

c# - 多线程访问内存中的大型字典对象 - 瓶颈?

c# - Unity table 游AI导致内存泄露

linux - 在 Linux 上中断线程中的系统调用

c++ - pthread_mutex_lock 上的段错误

c - 使用多个字符作为分隔符分割字符串

c - 为什么 main() 函数不返回浮点值?

c - 将 Fortran 零长度数组传递给 C 的正确方法是什么?

java - 等价于 Java 中的 await(x==0)