[英]Why when I use a mutex variable it didn't lock the code correctly? anytime the function return me a different answers
[英]why mutex didn't lock the variable
#define N 20
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
void *thread_main(void* arg){
pthread_mutex_lock(&lock);
long * i = (long*)arg;
printf("%ld\n", *i);
pthread_mutex_unlock(&lock);
return NULL;
}
int main()
{
pthread_t tid[N];
int rc;
for (long i = 0; i < N; i++) {
rc = pthread_create(&tid[i], NULL, thread_main, &i);
if (rc) {
fprintf(stderr, "ERROR: could not create thread\n");
return -1;
}
}
---thread join---
}
在这段代码中,我的输出是
7 7 7 7 7 7 8 9 10 10 6 12 13 14 20 20 20 20 20 20
不知道为什么它没有长时间锁定并将其打印为:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
有什么问题,这是解决这种情况的策略
该变量由for
循环修改,但该线程不保存互斥锁。 互斥锁没有锁定变量,因为您修改了变量而没有持有锁定。
您正在围绕打印 function 执行互斥锁。
这意味着一次只能打印一件事,但这并没有真正的帮助。 i
的值仍然可以更改,因为i++
在互斥锁之外。
您可能对i
的更改发生在互斥体内部。
我怀疑这是你想要的:
#include <stdio.h>
#include <pthread.h>
#define N 20
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
void *thread_main(void* arg){
pthread_mutex_lock(&lock);
long *i = (long*)arg;
// Modifications to i happen inside the mutex
printf("%ld\n", (*i)++);
pthread_mutex_unlock(&lock);
return NULL;
}
int main()
{
pthread_t tid[N];
int rc;
long i = 0;
// For/while loop does not modify value of i directly
while (i < N) {
rc = pthread_create(&tid[i], NULL, thread_main, &i);
if (rc) {
fprintf(stderr, "ERROR: could not create thread\n");
return -1;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.