C pthread_create并在main函数外部加入

时间:2017-11-11 21:42:19

标签: 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 libary的新手,我遇到了一个情况。一般描述如下。 我想在运行时根据输入创建线程并在main函数外部加入线程,所以这里我使用if statemnt创建一个新的 如果count是奇数,则为thread。 我希望所有线程使用相同的信号量和同步,但是当我运行代码时,它只是卡住了, 我想要像这样的输出

执行0,数字为0

执行1,数字为1

执行2,数字为2

执行3,数字为3

执行0,数字为4

执行4,数字为5

执行2,数字为6

执行0,数字为7 ...

这个想法可能吗?如果是的话,我的问题在哪里,谢谢你的帮助!

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

if (count % 2 == 0) {
            continue;
        }

用这个替换上面的代码,因为如果if statement为真,则计数值不会改变,continue语句将进入无限循环

if (count % 2 == 0) {
            count++;
            continue;
        }
相关问题