Linux 多线程编程入门--线程函数解释

上一篇 / 下一篇  2009-05-20 22:38:29 / 个人分类:Linux

我的栏目
  • 栏目:C/C++
创建线程:
int pthread_create(pthread_t *restrict thread,51Testing软件测试网p$} y#^"S3KUg
           
const pthread_attr_t *restrict attr,51Testing软件测试网+DjM:w&U{k?
           
void *(*start_routine)(void*), void *restrict arg);
参数:
      thread输出线程id
     attr 线程属性, 默认NULL
      start_routine线程执行函数
      arg线程执行参数  
note:函数成功返回0 否则返回错误码
头文件 pthread.h
库文件 pthread
 
退出线程:
int pthread_exit(void * value_ptr);
参数:
      value_ptr 线程返回值指针
note: ptrhead_exit()退出调用此函数的线程并释放该线程占用的资源
头文件 pthread.h
库文件 pthread
 
等待指定线程结束:
int pthread_join(pthread_t thread,void **value_ptr);
参数:
      thread一个有效的线程id
      value_ptr 接收线程返回值的指针
note:调用此函数的线程在指定的线程退出前将处于挂起状态或出现错误而直接返回
     如果value_ptr非NULL则value_ptr指向线程返回值的指针
     函数成功后指定的线程使用的资源将被释放
头文件 pthread.h
库文件 pthread
 
 
获取当前线程id:
pthread_t pthread_self(void);
参数:
      
note:返回当前函数的id
头文件 pthread.h
库文件 pthread
 
互斥:
说到多线程,最关心的就是数据访问/改变的同步问题。
windows下有临界区和信号事件等手段来防止多个线程同时读/写同一个数据,那么linux呢?
多线程变成时多使用互斥pthread_mutex_t来起到防止同时访问或改变同一数据.
 
创建互斥:
int pthread_mutex_init(pthread_mutex_t *restrict mutex,
BgRGT0                     
const pthread_mutexattr_t *restrict attr);
参数:
      mutex输出互斥id
     attr 互斥属性, 默认NULL
note:函数成功返回0 否则返回错误码
头文件 pthread.h
库文件 pthread
 
锁住互斥:
int pthread_mutex_lock(pthread_mutex_t *mutex);
参数:
      mutex互斥id
note:如果指定的互斥id已经被锁住那么呼叫线程在互斥id完全解锁前将
     一直处于挂起状态,否则将锁住互斥体
头文件 pthread.h
库文件 pthread
 
int pthread_mutex_trylock(pthread_mutex_t *mutex);
参数:
      mutex互斥id
note:如果指定的互斥id已经被锁住那么将直接返回一个错误,通过判断
     此错误来进行不同的处理
头文件 pthread.h
库文件 pthread
 
解锁互斥:
int pthread_mutex_unlock(pthread_mutex_t *mutex);
参数:
     mutex互斥id
note:如果指定的互斥id已经被锁住那么对其解锁
头文件 pthread.h
库文件 pthread
 
释放互斥:
int pthread_mutex_destroy(pthread_mutex_t *mutex);
参数:
     mutex互斥id
note:释放指定的mutex占用的资源
头文件 pthread.h
库文件 pthread
51Testing软件测试网&~3dm3}k| ~4R

TAG: 线程 Linux

 

评分:0

我来说两句

Open Toolbar