读书人

pthread 精简使用指南(一)

发布时间: 2012-09-17 12:06:51 作者: rapoo

pthread 简要使用指南(一)

POSIX thread 简称为pthread,Posix线程是一个POSIX标准线程。该标准定义内部API创建和操纵线程。 Pthreads定义了一套 C程序语言类型、函数与常量,它以 pthread.h 头文件和一个线程库实现。

直接上代码,简单明了。


#include <pthread.h>#include <stdlib.h>#include <stdio.h>#include <unistd.h>#include <string.h>// 线程IDpthread_t       ntid;// 互斥对象pthread_mutex_t mutex;int             count;void printids(const char *s){    pid_t pid;    pthread_t tid;    pid = getpid();    tid = pthread_self();    printf("%s pid %u tid %u (0x%x)\n", s, (unsigned int)pid,        (unsigned int)tid, (unsigned int)tid);}// 线程函数void *thr_fn(void *arg){    printids("new thread begin\n");    // 加锁    pthread_mutex_lock(&mutex);    printids("new thread:");    int i=0;    for ( ; i < 5; ++i )    {        printf("thr_fn runing %d\n", count++);    }    // 释放互斥锁    pthread_mutex_unlock(&mutex);    return ( (void*)100);}int main(void){    int err;    count = 0;    // 初始化互斥对象    pthread_mutex_init(&mutex, NULL);    // 创建线程    err = pthread_create(&ntid, NULL, thr_fn, NULL);    if ( 0 != err )    {        printf("can't create thread:%s\n", strerror(err));    }    // sleep(5);    pthread_mutex_lock(&mutex);      printids("main thread:");    int i=0;    for ( ; i < 5; ++i )    {        printf("main runing %d \n", count++);    }    sleep(1);    pthread_mutex_unlock(&mutex);    int **ret;    pthread_join(ntid, (void**)ret);    printf("thr_fn return %d\n", *ret);    pthread_mutex_destroy(&mutex);    return 0;}


这个例子,用到了pthread的数据结构:
pthread_t, 这个结构来标识线程ID;
pthread_mutex_t, 这个用来做互斥;


用到了如下函数:
pthread_self() : 获得线程自身的ID;

pthread_create(&ntid, NULL, thr_fn, NULL): 线程创建函数
原型:int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void*(*start_routine)(void*), void *arg)。
tid : 新创建线程的线程ID;
attr: 指定新创建线程的线程属性,为NULL即为使用默认属性;
start_routine : 这是一个函数指针,用来指向线程函数;
arg : 传递给线程函数的指针;
返回值 : 0代表成功。 失败,返回的则是错误号。

pthread_join(ntid, (void*)ret):等待一个线程的结束
原型:int pthread_join(pthread_t thread, void **retval);
thread : 需要等待的线程的ID;
retval : 存放等待线程的返回值;
返回值 : 0代表成功。 失败,返回的则是错误号。

pthread_mutex_init(&mutex, NULL):初始化互斥锁,以动态方式创建互斥锁
原型:int pthread_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): 销毁锁对象


编译的时候,需要加上编译参数“-lpthread”。
可以屏蔽pthread_mutex_lock(),pthread_mutex_unlock()看下没有互斥的结果。



读书人网 >编程

热点推荐