有人能告诉我我的密码出了什么问题吗。我希望一次只访问一个线程来访问关键区域,但是所有线程都会进入。
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
pthread_t th[5];
pthread_mutex_t mutex_for_some_value;
int value;
void * thread_talk(void * arguments) {
while (1) {
pthread_mutex_lock(&mutex_for_some_value);
printf("\n Now Accessed by %d", *((int*) arguments));
pthread_mutex_unlock(&mutex_for_some_value);
sleep(2);
printf("\n\n Thread %d is left critical section", *((int*) arguments));
}
return NULL;
}
int main(int argc, char **argv) {
int count[5] = { 1, 2, 3, 4, 5 };
printf("\n %d", pthread_mutex_init(&mutex_for_some_value, NULL));
for (int i = 0; i < 5; i++) {
printf("\n Creating %d thread", count[i]);
pthread_create(&th[i], NULL, &thread_talk, (void*) &count[i]);
}
for (int i = 0; i < 5; ++i) {
pthread_join(th[i], NULL);
}
pthread_mutex_destroy(&mutex_for_some_value);
printf("\n Main done");
return 0;
}现在,由于互斥是存在的,所以没有两个线程应该进入我的关键区域。但输出是
0创建1个线程
创建2个线程
创建3个线程
创建4个线程
创建5个线程
现在4人访问
现在被3访问
现在由2访问
现在由1人访问
现在5人访问
线程4的关键部分现在由4访问。
线程3的关键部分现在由3访问。
线程1的关键部分现在由1访问。
线程2的关键部分现在由2访问。
线程5是左边的关键部分。
发布于 2013-10-11 07:35:50
这句话:
sleep(2)将延迟“线程X离开关键部分”的输出,直到另一个线程打印“现在被Y访问”之后。锁应该还能用。
https://stackoverflow.com/questions/19312589
复制相似问题