linux中的条件变量解锁c

时间:2016-12-12 23:51:33

标签: c linux condition-variable

这是我创建的一些代码,只是为了测试一些关于条件变量和互斥体的东西。它只是应该数到10,但由于某种原因,工作线程一直停在printlock mutex上,因为主线程在等待printcond时没有被唤醒。 这是我的输出:

"I have this many threads: 7
This is my 1 time running, and my number is 0!
This is my 2 time running, and my number is 1!"

我必须遗漏一些非常明显的条件变量。我发信号打印后尝试解锁工作线程中的printlock,这使得代码运行,但是主线程只打印最后一个值来获取它。我希望主线程打印所有1-10的“我得到的数字”。我怎么做?我无法理解这些东西的逻辑结构,我到处寻找解决方案。任何帮助表示赞赏。

pthread_mutex_t varlock;
pthread_mutex_t printlock;
pthread_cond_t printcond;

void *worker(void *args)
{
int * count = args;
int run = 1;
while(1==1)
{
    pthread_mutex_lock(&varlock);
    if(*count == 10)
    {
        pthread_mutex_unlock(&varlock);
        printf("I am a thread exiting\n");
        return NULL;
    }
    else
    {
        printf("This is my %d time running, and my number is %d!\n", run, *count);
        pthread_mutex_lock(&printlock);
        pthread_cond_signal(&printcond);
        *count = *count +1;
        run++;
    }
    pthread_mutex_unlock(&varlock);
}
}

int main(int argc, char **argv)
{
int num = 7;
printf("I have this many threads: %d\n", num);
int * count = malloc(sizeof(int));
*count = 0;
if (pthread_mutex_init(&varlock, NULL) != 0)
{
    printf("mmult: Failed initializing mutex\n");
    return 1;
}
if (pthread_mutex_init(&printlock, NULL) != 0)
{
    printf("mmult: Failed initializing mutex\n");
    return 1;
}
pthread_mutex_lock(&printlock);
int err=pthread_cond_init(&printcond, NULL);
//Create the threads
pthread_t tid[num];
int i;
for(i = 0; i < num; i++)
{
    err = pthread_create(&(tid[i]),NULL,worker, count);
    if(err)
    {
        perror("mmult: Failed creating thread\n");
        return 1;
    }
}
while(1==1)
{
    if(*count == 10)
    {
        break;
    }
    pthread_cond_wait(&printcond, &printlock);
    printf("The number I got is %d.\n", *count);
    pthread_mutex_unlock(&printlock);
}
//Join all the threads
int status;
for(i = 0; i < num; i++)
{
    pthread_join(tid[i],(void **)&status);
}
printf("Now that I have finished, the count is %d.\n", *count);
return 0;
}

1 个答案:

答案 0 :(得分:1)

你有很多错误,但最明显的一个是你的第二个while(1==1)循环解锁互斥锁但不锁定它。因此,如果您进行循环,则可以解锁已解锁的互斥锁。这是一个错误。

你的第一个while(1==1)循环也有错误。解锁互斥锁只是为了立即再锁定它。您认为这有什么用途?