考虑下一个代码块 -怪异pthread_mutex_t行为
#include <iostream>
using namespace std;
int sharedIndex = 10;
pthread_mutex_t mutex;
void* foo(void* arg)
{
while(sharedIndex >= 0)
{
pthread_mutex_lock(&mutex);
cout << sharedIndex << endl;
sharedIndex--;
pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main() {
pthread_t p1;
pthread_t p2;
pthread_t p3;
pthread_create(&p1, NULL, foo, NULL);
pthread_create(&p2, NULL, foo, NULL);
pthread_create(&p3, NULL, foo, NULL);
pthread_join(p1, NULL);
pthread_join(p2, NULL);
pthread_join(p3, NULL);
return 0;
}
我只是创建了三个pthreads
并给他们所有相同功能foo
,在此希望每个线程,在其反过来,将打印和递减sharedIndex
。
但这是输出 -
10
9
8
7
6
5
4
3
2
1
0
-1
-2
- 我不明白为什么当
sharedIndex
达到0 sharedIndex
由mutex
保护的进程不会停止。在它变成0之后它是如何访问的?线程是不是应该直接跳至return NULL;
?
编辑
此外,似乎只有第一个线程递减sharedIndex
。 为什么不是每个线程都在递减共享资源? 这里有一个修正后的输出 -
Current thread: 140594495477504
10
Current thread: 140594495477504
9
Current thread: 140594495477504
8
Current thread: 140594495477504
7
Current thread: 140594495477504
6
Current thread: 140594495477504
5
Current thread: 140594495477504
4
Current thread: 140594495477504
3
Current thread: 140594495477504
2
Current thread: 140594495477504
1
Current thread: 140594495477504
0
Current thread: 140594495477504
Current thread: 140594478692096
Current thread: 140594487084800
我希望所有的线程将递减共享源代码 - 这意味着,每一个开关CONTEX,不同的线程将访问资源,做它的事。
尝试在程序的最后创建线程和“pthread_mutex_destroy”之前调用'pthread_mutex_init' – mausik
为什么不尝试在代码中修复未定义的行为并查看它是否有帮助? –
我确实改变了代码,它工作。但仍然 - 只有一个线程递减资源 –