为什么变量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;
}
答案 0 :(得分:2)
由于这一行:
if(a > 0) { a--; }
a如果在等于或小于0时不递减,则不能等于-1 ...