【发布时间】:2017-05-25 00:40:59
【问题描述】:
我有一个问题线程很长一段时间。这段代码应该有一个工作线程在主线程打印出共享整数时递增共享整数的值。但是,我没有得到预期的输出。
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
pthread_mutex_t lock;
int shared_data = 0; //shared data
// Often shared data is more complex than just an int.
void* thread_function(void* arg)
{
int i;
for (i = 0; i < 10; ++i)
{
// Access the shared data here.
pthread_mutex_lock(&lock);
shared_data++;
pthread_mutex_unlock(&lock);
}
return NULL;
}
int main(void)
{
pthread_t thread;
int i;
void* exit_status;
// Initialize the mutex before trying to use it.
pthread_mutex_init(&lock, NULL);
pthread_create(&thread, NULL, thread_function, NULL);
// Try to use the shared data.
for (i = 0; i < 10; ++i)
{
sleep(1);
pthread_mutex_lock(&lock);
printf ("\r for i= %d Shared integer 's value = %d\n", i, shared_data);
pthread_mutex_unlock(&lock);
}
printf("\n");
pthread_join(thread, &exit_status);
// Clean up the mutex when we are finished with it.
pthread_mutex_destroy(&lock);
return 0;
}
这是我的期望:
for i=0 Shared Integer 's value = 0
for i=1 Shared Integer 's value = 1
for i=3 Shared Integer 's value = 2
...
for i=10 Shared Integer 's value =10
但结果是:
for i=0 Shared Integer 's value = 0
for i=1 Shared Integer 's value = 10
for i=3 Shared Integer 's value = 10
...
for i=10 Shared Integer 's value =10
那我该如何解决呢?
【问题讨论】:
-
请使用一致且适当的缩进格式化您的代码以使其可读。
-
然后向我们解释您认为程序的哪一部分会按照您描述的方式对输出进行排序。您似乎假设主线程将获得锁,然后是子线程,然后是主线程,然后是子线程,等等。没有这样的保证。
-
第一次主迭代的连接等待线程完成,因此在第二次迭代中你得到 10 的最终结果。
-
@NikolaiFetissov 谢谢,我已经编辑了我的代码格式,实际上我期待线程增加共享数据的值,然后主循环中的循环打印值,从0 到 10 ,这里不是这样
-
为什么在需要两个信号量的情况下,开发人员总是滥用互斥锁?