首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 操作系统 > UNIXLINUX >

pthread多线程有关问题

2013-12-28 
pthread多线程问题#include stdio.h#include pthread.hint count 0pthread_cond_t xx PTHREAD_CO

pthread多线程问题

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

int count = 0;
pthread_cond_t xx = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mx = PTHREAD_MUTEX_INITIALIZER;

void* a(void* c) {
    static int i=0;
    while(true) {
        pthread_mutex_lock(&mx);
        if(i>=30) {
            pthread_mutex_unlock(&mx);
            break;
        }
        if(i == (*((int*)c))) pthread_cond_broadcast(&xx);
        else pthread_cond_wait(&xx, &mx);
        printf("%d\n", i++);
        pthread_mutex_unlock(&mx);
    }
    return NULL;
}

int main()
{
    pthread_t x[30];
    int ax[30];
    for(int i=0; i<30; i++) {
        ax[i] = i;
        pthread_create(&x[i], NULL, a, &ax[i]);
    }
    for(int i=0; i<30; i++) pthread_join(x[i], NULL);
    return 0;
}

请问我的线程为什么停下了?
[解决办法]
死锁了。
因为你循环里同时创建了多个线程,线程一上来就把 mx 锁住。而且pthread_cond_wait会再次将 mx 锁一下。所以,理论上你的每个线程都会对 mx 加两次锁,款且你这还是这么多线程,不死锁才怪。

热点排行