【问题标题】:Pthreads: Main overwrites mutex lockPthreads:主要覆盖互斥锁
【发布时间】:2014-09-04 23:18:03
【问题描述】:

我是线程编程的新手,我想测试互斥锁功能。所以我编写了以下代码来测试它。

**thread_test.h

...
extern int flags;
extern pthread_mutex my_mutex;
...

**thread_test.c

...
#include"thread_test.h"
...    
void * thread_test(void *thread_parameters)
{
long tid = (long) thread_parameters;

pthread_mutex_lock(&my_mutex);
++flags;
printf("**THREAD %d** started. Flag value is %d.\n",tid, flags);
sleep(6);
pthread_mutex_unlock(&my_mutex);

pthread_exit(NULL);
}
...

**main.c

...
#include"thread_test.h"
...
#define THREADS 5
pthread_t threads[THREADS];
pthread_mutex_t my_mutex;
int     flags = 0;
...
int main(){
int rct;
for(rct = 0; rct<THREADS; rct++)
if(pthread_create(&threads[rct],NULL, thread_test, (void *)rct))
   printf("ERROR!")
else
   {
   sleep(1);
   printf("Thread %d initialised in main and the flags value is %d.\n", rct,flags);
   }

pthread_mutex_destroy(&my_mutex);
...

看来,即使我在子线程中锁定了互斥锁,主程序还是会在线程拥有互斥锁时以某种方式覆盖互斥锁,并为变量标志分配一个新值..

有人知道为什么会这样吗?

【问题讨论】:

  • 很可能,main() 在任何线程有机会运行之前就到达了pthread_mutex_destroy()(我不确定pthread_mutex_destroy() 是否真的关心互斥锁是否被锁定或不...)。在销毁互斥锁​​之前,您可能应该 pthread_join() 所有线程...
  • main() 已经更改了标志变量,因为第一个线程在sleep(6) 中并且在它破坏互斥锁之前。输出如下所示:**THREAD 0** started.The current flag is 1.Thread 0 initialized in main and the flag value is : 1Thread 1 initialized in main and the flag value is : 1Thread 2 initialized in main and the flag value is : 2 Thread 3 initialized in main and the flag value is : 3 Thread 4 initialized in main and the flag value is : 4 **THREAD 1** started.The current flag is 5. **THREAD 2** started.The current flag is 6. ...等..

标签: c multithreading pthreads


【解决方案1】:

据我所知,您的代码中有几个错误,如果您打开所有警告,编译器应该会告诉您其中的一部分。

  • pthread_mutex_t 变量必须被初始化。对于在定义点使用= PTHREAD_MUTEX_INITIALIZER 的静态初始化就足够了。 (而且销毁另一端的静态互斥体并没有多大意义。)

  • 在您提供的代码 sn-p 中,没有 thread_test 的声明对 main 可见

  • 在线程终止之前退出main(并销毁互斥锁​​)。你可以这样做,但是你必须在main 中使用一个explit pthread_exit(并且绝对不要这样做)。常用的做法是不这样做,而是对所有已创建的线程使用pthread_join

此外,您可以在发布之前缩进您的代码,这将有助于使其更具可读性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-23
    相关资源
    最近更新 更多