leobegin2016 2017-05-08 16:08 采纳率: 100%
浏览 1080
已采纳

linux下多线程加锁 编译通不够

#include
#include
#include
#include
#include
#include
#include

void *thread_function(void *arg);

int run_now = 1;

pthread_mutex_t work_mutex;

int main()
{
int res;
int print_count1 = 0;
pthread_t a_thread;
if(pthread_mutex_init(&work_mutex,NULL) != 0)
{

perror("Mutex init failed");
exit(1);
}
if(pthread_mutex_lock(&work_mutex) !=0)
{

perror("Lock failed");
exit(1);
}
else
printf("main lock\n");
while(print_count1++<5)
{
if(run_now == 1)
{
printf("main thread is run\n");
run_now = 2;
}
else
{
printf("main thread is sleep\n");
sleep(1);
}
}

if(pthread_mutex_unlock(&work_mutex) !=0)
{
    perror("unlock failed");
    exit(1);
}
else
printf("main unlock\n");
pthread_mutex_destory(&work_mutex);
pthread_join(a_thread,NULL);
exit(0);

}

void *thread_function(void *arg)
{
int print_count2 = 0;
sleep(1);
if(pthread_mutex_lock(&work_mutex) != 0)
{
perror("Lock failed");
exit(1);
}
else
printf("function lock\n");
while(print_count2++<5)
{
if(run_now == 2)
{
printf("function thread is run\n");
run_now = 1;
}
else
{
printf("function thread is sleep\n");
sleep(1);
}
}
if(pthread_mutex_unlock(&work_mutex) != 0)
{
perror("unlock failed");
exit(1);
}
else
printf("function unlock\n");
pthread_exit(NULL);
}
图片说明

  • 写回答

3条回答 默认 最新

  • 普通网友 2017-05-08 23:20
    关注

    拼写错了,当然没定义

     pthread_mutex_destroy
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog