打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
linux C 多线程/线程池编程 同步实例
userphoto

2017.01.08

关注

在多线程、线程池编程中经常会遇到同步的问题。

1.创建线程

  函数原型:int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);

  参数:thread指向线程id的指针;attr指向线程属性的指针;第三个为执行的方法的函数指针;arg指向给方法传递的参数的指针。

2.互斥变量

  (1)互斥变量   pthread_mutex_t

  (2)互斥变量锁定  int pthread_mutex_lock(pthread_mutex_t *mutex);

  (3)互斥变量解锁  int pthread_mutex_unlock(pthread_mutex_t *mutex);

3.多线程/线程池实例

下面是一个Linux C多线程同步取任务的操作,设定任务总量用MAX_JOB表示,当前任务编号用current_job表示。

文件名:a.c

 1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <pthread.h> 4 #include <unistd.h> 5 #define MAX_JOB 50 ///任务总量 6  7 typedef struct { 8   pthread_t        thread_tid; 9 } Thread;10 11 Thread    *tptr;12 int current_job=1;    ///当前任务编号13 pthread_mutex_t    lock = PTHREAD_MUTEX_INITIALIZER;   ///互斥锁14 15 void* thread_run(void* arg)16 {17     int jobid;18     for(;;)19     {20         pthread_mutex_lock(&lock);21         if(current_job>MAX_JOB) ///任务已经完成22             jobid=-1;23         else24         {25             jobid=current_job;26             current_job++;27         }28         pthread_mutex_unlock(&lock);29 30         if(jobid==-1)31         {32             printf("thread %d over\n",(int)arg);33             break;34         }35         else36             printf("thread %d get the job %d\n",(int)arg,jobid);37     }38     return 0;39 }40 41 int main () {42     int i;43     int threadNum;  ///线程个数44     scanf("%d",&threadNum);45     tptr=(Thread*)malloc(sizeof(Thread)*threadNum);46 47     for(i=0;i<threadNum;i++)    ///创建threadNum个线程48         pthread_create(&tptr[i].thread_tid, NULL, &thread_run, (void *) i);49 50     for(i=0;i<threadNum;i++)51     {52         if(current_job>MAX_JOB)53         {54             printf("ALL OVER!!!\n");55             break;56         }57         else58         {59             printf("OK\n");60             sleep(1);    ///停留1秒61         }62 63     }64     sleep(4);    ///停留4秒,等待最后一批任务的完成65     return 0;66 }

编译:gcc -lpthread a.c -o a

执行输出:./a

 

 

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
[转]linux-多线程
多线程条件变量的加深理解
200行C代码实现简单线程池 - Linux内核编程 - 举世无双的学习之路
Linux 线程池
linux下C实现多线程
pthread的各种同步机制
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服