C Pthreads:Main覆盖互斥锁

C Pthreads:Main覆盖互斥锁,c,multithreading,pthreads,C,Multithreading,Pthreads,我是线程编程方面的新手,我想测试互斥函数的功能。为了测试它,我编写了以下程序 **螺纹试验 ... extern int flags; extern pthread_mutex my_mutex; ... **螺纹试验 ... #include"thread_test.h" ... void * thread_test(void *thread_parameters) { long tid = (long) thread_parameters; pthread_mutex_lock(

我是线程编程方面的新手,我想测试互斥函数的功能。为了测试它,我编写了以下程序

**螺纹试验

...
extern int flags;
extern pthread_mutex my_mutex;
...
**螺纹试验

...
#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);
...
。。。
#包括“thread_test.h”
...
#定义线程5
pthread_t线程[线程];
pthread_mutex_t my_mutex;
int标志=0;
...
int main(){
int rct;

对于(rct=0;rct,据我所知,您的代码中有几个错误,其中一部分是编译器应该告诉您是否打开了所有警告

  • pthread\u mutex\u t
    必须初始化变量。对于静态初始化,在定义点使用
    =pthread\u mutex\u初始值设定项就足够了。(在另一端销毁静态互斥对象没有多大意义。)

  • 在您给出的代码片段中,没有对
    main
    可见的
    thread\u test
    的声明

  • 在线程终止之前退出
    main
    (并销毁互斥锁)。您可以这样做,但随后必须在
    main
    中使用explicit
    pthread\u exit
    (并且最终不执行销毁操作)。常用的方法不是这样做,而是对已创建的所有线程使用
    pthread\u join

另外,您可以在这里发布之前缩进代码,这将大大有助于提高代码的可读性。

最有可能的是,
main()
在任何线程都没有机会运行之前就进入了
pthread\u mutex\u destroy()
(我不确定
pthread\u mutex\u destroy())
甚至真正关心互斥锁是否被锁定…。在销毁互斥锁之前,您可能应该
pthread\u join()
所有线程…
main()
更改标志变量,因为第一个线程处于
睡眠状态(6)
在销毁互斥锁之前。输出如下所示:
**线程0**已启动。当前标志为1。
线程0在main中初始化,标志值为:1
线程1在main中初始化,标志值为:1
线程2在main中初始化,标志值为:2
线程3初始化在main中序列化,标志值为:3
线程4在main中初始化,标志值为:4
**线程1**已启动。当前标志为5。
**线程2**已启动。当前标志为6。
..等等。。