pthread初识

来源:互联网 发布:程序员的算法趣题 pdf 编辑:程序博客网 时间:2024/05/21 17:50

1.    sleep(unsignedmilliseconds)

需要头文件:#include <unistd.h>

单位为秒(如果需要更精确可以用usleep单位为微秒)

返回值:若进程/线程挂起到参数milliseconds所指定的时间则返回0,若有信号中断则返回剩余秒数。

 

2.    创建线程:

pthread_create(&id,NULL,thread,NULL);

函数原型:int pthread_create(pthread_t *restrict tidp , constpthread_attr_t *restrict attr , void *(*start_rtn)(void) , void *restrict arg);

  返回值:若是成功建立线程返回0,否则返回错误的编号。

  形式参数:pthread_t *restrict tidp要创建的线程的线程id指针;constpthread_attr_t *restrict attr创建线程时的线程属性;void*(start_rtn)(void)返回值是void类型的指针函数;void *restrict arg start_rtn的形参。

 

3.    线程挂起

该函数的作用使得当前线程挂起,等待另一个线程返回才继续执行。也就是说当程序运行到这个地方时,程序会先停止,然后等线程id为thread的这个线程返回,然后程序才会断续执行。

pthread_join(id,NULL);

函数原型:int pthread_join( pthread_t thread, void**value_ptr);

参数说明如下:thread等待退出线程的线程号;value_ptr退出线程的返回值。

 

4. 线程退出

函数原型:void pthread_exit(void *rval_ptr);

 

5. 获取当前线程ID

 函数原型:pthread_t pthread_self(void);

 

6. 互斥锁

  pthread_mutex_init(&mutex, NULL):初始化互斥锁,以动态方式创建互斥锁
   
原型:intpthread_mutex_init(pthread_mutex_t *restrict mutex,
             const pthread_mutexattr_t *restrict attr);
    mutex : 被初始化的锁对象; 
    attr  : 指定新建互斥锁的属性。为NULL,则使用默认的互斥锁属性,默认属性为快速互斥锁。

   pthread_mutex_lock(&mutex)     :加锁
    pthread_mutex_unlock(&mutex) :
释放锁

  pthread_mutex_destroy(&mutex):销毁锁对象

 通过互斥量可以保证数据在同一时刻只能被一个线程访问,其他线程阻塞,锁住互斥量的线程释放互斥量时,阻塞在互斥量上的线程都被唤醒,竞争这个互斥量,最终只有一个线程获得互斥量锁定继续运行,其他线程继续进入阻塞状态。


7. 条件锁:

 创建pthread_cond_init;销毁pthread_cond_destroy;触发pthread_cond_signal;广播pthread_cond_broadcast S;等待pthread_cond_wait。 



 8.C++的类中,普通成员函数不能作为pthread_create的线程函数,如果要作为pthread_create中的线程函数,必须是static !


#include<iostream>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>

using namespace std;

pthread_t id;
pthread_mutex_t mutex;//互斥变量
int count;

void printids(const char *s){
pid_t pid;
pthread_t tid;
pid = getpid();
tid =pthread_self();
cout<<s<<"  "<<pid<<" pid "<<tid<<" tid "<<endl;
}

void* thread_fun(void *arg){
printids("new thread begin...");
pthread_mutex_lock(&mutex);
printids("new thread:");
int i = 0;
for( ; i<5;i++){
cout<<"thread_fun runing ..."<<count++<<endl;
}
pthread_mutex_unlock(&mutex);
return NULL;
}

int main(){
int err;
count = 0;
pthread_mutex_init(&mutex ,NULL);
err = pthread_create(&id ,NULL,thread_fun ,NULL);
if(err != 0)
cout<<"can't create thread"<<endl;
pthread_mutex_lock(&mutex);
printids("main thread");
for(int i =0 ;i<5;++i)
cout<<"main running ..."<<count++<<endl;
sleep(1);
pthread_mutex_unlock(&mutex);

pthread_join(id ,NULL);

pthread_mutex_destroy(&mutex);

return 0;
}

0 0