zoukankan      html  css  js  c++  java
  • linux C 多线程/线程池编程 同步实例

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

    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         else
    24         {
    25             jobid=current_job;
    26             current_job++;
    27         }
    28         pthread_mutex_unlock(&lock);
    29 
    30         if(jobid==-1)
    31         {
    32             printf("thread %d over
    ",(int)arg);
    33             break;
    34         }
    35         else
    36             printf("thread %d get the job %d
    ",(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!!!
    ");
    55             break;
    56         }
    57         else
    58         {
    59             printf("OK
    ");
    60             sleep(1);    ///停留1秒
    61         }
    62 
    63     }
    64     sleep(4);    ///停留4秒,等待最后一批任务的完成
    65     return 0;
    66 }

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

    执行输出:./a

  • 相关阅读:
    改变,必须改变
    厦门四日
    再谈兴趣的重要性,人的差别及如何认识自我
    xcode svn checkout的项目无法真机运行解决办法
    [转]c的fopen()打开文件的模式,第二个参数
    cocos2dx 横板游戏触屏人物和背景移动 方法1
    简单的小球移动隐含的bug
    使用CCHttpRequest后要记得release(),否则内存泄漏
    资源路径问题 (ios平台)
    cocos2dx 横板游戏触屏人物和背景移动 方法2
  • 原文地址:https://www.cnblogs.com/xudong-bupt/p/3479385.html
Copyright © 2011-2022 走看看