Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 在多线程程序中使用pthread_互斥体_C_Linux_Multithreading_Thread Synchronization - Fatal编程技术网

C 在多线程程序中使用pthread_互斥体

C 在多线程程序中使用pthread_互斥体,c,linux,multithreading,thread-synchronization,C,Linux,Multithreading,Thread Synchronization,我正在编写一个创建三个线程的代码。现在使用pthread_互斥体如何同步它们? 假设我有这种类型的代码:- #include<stdio.h> #include<pthread.h> void *function1(void *ptr) { do something on a buffer; } void *function2(void *ptr) { do samething else but ob the same buffer; } void *

我正在编写一个创建三个线程的代码。现在使用pthread_互斥体如何同步它们? 假设我有这种类型的代码:-

#include<stdio.h>
#include<pthread.h>

void *function1(void *ptr)
{

   do something on a buffer;
}

void *function2(void *ptr)
{
  do samething else but ob the same buffer;
 }

void *function(void *ptr)
{
  do samething else again on buffer;
}


main()
{ 
   pthread_t t1,t2,t3);
   int a,b,c;
   a= creates a thread using pthread_create(&t1,NULL,func1,NULL);
   b= creates a thread using pthread_create(&t2,NULL,func2,NULL);
   c= creates a thread using pthread_create(&t3,NULL,func1,NULL);

 and after that pthread_join wait till all the threads gets finished;
}
#包括
#包括
void*function1(void*ptr)
{
在缓冲区上做某事;
}
void*function2(void*ptr)
{
执行相同的操作,但使用相同的缓冲区;
}
void*函数(void*ptr)
{
在缓冲区上再次执行同样的操作;
}
main()
{ 
pthread_t t1、t2、t3);
INTA、b、c;
a=使用pthread_create创建线程(&t1,NULL,func1,NULL);
b=使用pthread_create创建线程(&t2,NULL,func2,NULL);
c=使用pthread_create创建线程(&t3,NULL,func1,NULL);
在pthread_join之后,等待所有线程完成;
}
但正如您所看到的,当您执行这样的操作时,所有线程都同时启动,结果并不像预期的那样。现在,我们如何使用pthread_互斥锁来锁定和解锁同一个缓冲区,以便一次只有一个线程可以处理它? 我也希望t1先出现,然后是t2,然后是t3。基本上我必须设置优先级,怎么做?

请参见此示例:

你必须读一点书,但这很容易。 您必须声明并初始化互斥锁: pthread_mutex_t myMutex; pthread_mutex_init(&myMutex,NULL)

使用它:

pthread_mutex_lock(&myMutex)

//在这里使用缓冲区

pthread_mutex_unlock(&myMutex)

另外,不要忘记清理:
pthread_mutex_destroy(&myMutex)

有些东西告诉我,如果打开任何手册或在互联网上查找示例,你会发现成千上万的代码示例和解释……正如@KerrekSB所说,首先搜索答案,然后提问。你的问题很基本,即使你读过pthread mtexes的用法,你也会找到答案。我读过pthread_mutex_lock(),但当我实现时,输出并没有那么扩展。我想先调用t1,然后调用t2,然后调用t3,但是当我编译代码时,顺序是随机的。我怎么才能摆脱这个问题呢?我读过关于pthread_mutex_lock()的文章,但是当我实现时,输出并没有那么扩展。我想先调用t1,然后调用t2,然后调用t3,但是当我编译代码时,顺序是随机的。我怎样才能摆脱它?@user2714823你不能。线程可以在任何时候执行,正如您所说,这是随机的。在上面的示例中,我希望先执行thread1,然后执行thread2和thread3。可能吗?那你为什么需要线程呢?您可以调用这些方法。但是,如果您仍然希望以顺序方式调用线程(比如出于实验原因),则可以使用pthread_join等待线程终止。基本上,您启动t1,然后使用pthread_join等待它。然后启动t2并再次使用pthread_join等。