Pthread - 执行时间

时间:2014-04-20 19:22:09

标签: c++ multithreading

为什么变量a不假设值0或-1而是0和1?

pthread_mutex_t stop = PTHREAD_MUTEX_INITIALIZER;
int a = 1;

void* decrement(void* arg)
{ 
    pthread_mutex_lock(&stop);
    if(a > 0) { a--; } 
    pthread_mutex_unlock(&stop);
    pthread_exit(NULL);
}

int main()
{
    pthread_t tid, tid1;
    pthread_attr_t tattr;
    pthread_attr_init(&tattr);
    pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_DETACHED);
    pthread_create(&tid, &tattr, decrement, NULL);
    pthread_detach(tid);
    pthread_create(&tid1, &tattr, decrement, NULL);
    pthread_detach(tid1);   
    cout << a << endl;
}

1 个答案:

答案 0 :(得分:2)

由于这一行:

if(a > 0) { a--; }

a如果在等于或小于0时​​不递减,则不能等于-1 ...