Linux多线程通信

来源:互联网 发布:cf2016刷枪软件 编辑:程序博客网 时间:2024/05/29 18:13

Linux 多线程通信

 

一.进程与线程

进程通信:资源分配的最小单位

有独立的地址空间,十分耗内存。

 

线程通信:程序执行的最小单位

无独立的地址空间(多任务操作模式,多线程共享地址空间,节省开销)

          线程间有方便的通信机制(共享数据,有独立堆栈和局部变量

         

 

二.多线程API

1.pthread_create

函数的作用:创建一个线程

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

函数的参数:thread:线程的标识符

            attr:线程的属性,一般设为NULL

            start_routine:线程的执行函数

            arg:传入到线程执行函数的参数

返回 值:成功:0,出错:-1

头文 件:#include <pthread.h>

 

2.pthread_exit

函数的作用:线程的退出

函数的原型:void pthread_exit(void * retval)

 

3.pthread_join

函数的作用:等待线程的退出

函数的原型:pthread_join(pthread_t th,void ** thread_return)

函数的参数:th:线程的标识符

            thread_return:不为NULL时,存储线程结束时返回值

返回 值:成功:0  出错:<0

 

三.            多线程应用

1.thread_create.c

#include <stdio.h>  #include <pthread.h>     void *myThread1(void)  {      int i;      for (i=0; i<100; i++)      {          printf("This is the 1st pthread,created by zieckey.\n");          sleep(1);//Let this thread to sleep 1 second,and then continue to run      }  }  void *myThread2(void)  {      int i;      for (i=0; i<100; i++)      {          printf("This is the 2st pthread,created by zieckey.\n");          sleep(1);      }  }     int main()  {      int i=0, ret=0;      pthread_t id1,id2;            ret = pthread_create(&id1, NULL, (void*)myThread1, NULL);      if (ret)      {          printf("Create pthread error!\n");          return 1;      }            ret = pthread_create(&id2, NULL, (void*)myThread2, NULL);      if (ret)      {          printf("Create pthread error!\n");          return 1;      }         pthread_join(id1, 0);      pthread_join(id2, NULL);            return 0;  }  

2.thread_struct.c

#include <stdio.h>  #include <pthread.h>  #include <unistd.h>  #include <stdlib.h>     struct menber  {      int a;      char *s;  };     void *create(void *arg)  {      struct menber *temp;      temp=(struct menber *)arg;      printf("menber->a = %d  \n",temp->a);      printf("menber->s = %s  \n",temp->s);      return (void *)0;  }     int main(int argc,char *argv[])  {      pthread_t tidp;      int error;      struct menber *b;      b=(struct menber *)malloc( sizeof(struct menber) );      b->a = 4;      b->s = "zieckey";         error = pthread_create(&tidp, NULL, create, (void *)b);         if( error )      {          printf("phread is not created...\n");          return -1;      }      sleep(1);      printf("pthread is created...\n");      return 0;  }  



 

 

四.线程之间对资源的竞争:

1.互斥锁Mutex

    基本操作:

互斥锁初始化:pthread_mutex_init()

互斥锁上锁:pthread_mutex_lock()

互斥锁判断上锁:pthread_mutex_trylock()

互斥锁接锁:pthread_mutex_unlock()

消除互斥锁:pthread_mutex_destroy()

 

2.信号灯Semaphore

信号量初始化:sem_init

PV操作:

int sem_wait(sem_t*sem)   --P操作

            int sem_trywait(sem_t*sem)

            int sem_post(sem_t*sem)   --V操作

            intsem_getvalue(sem_t *sem)

   int sem_destroy(sem_t*sem)

 

3.条件变量Conditions

 

0 0