linux多线程编程之一多线程数据同步及相关api使用示例

原文:https://my.oschina.net/elitetao/blog/776097

摘要: linux c++ 多线程编程 多线程数据同步

多线程的使用在编码过程中非常常见,如果快速的理解和掌握linux下的多线程编程呢?下文即将为您揭晓一.linux多线程基本的创建及相关API使用:

1.线程的创建: int pthread_create(pthread_t thread, const pthread_attr_t attr, void (start_routine) (void ), void arg); 4个参数: 第一个参数:指向线程标示符pthread_t的指针; 第二个参数:设置线程的属性 第三个参数:线程运行函数的起始地址 第四个参数:运行函数的参数

2.退出 pthread_exit 函数使线程退出并返回一个空指针类型的值,该值可以由下面即将介绍的函数pthread_join来获取。

3.等待函数pthread_join用来等待一个线程的结束。 int pthread_join(pthread_t thread, void **retval); 参数 :thread: 线程标识符,即线程ID,标识唯一线程。 retval: 用户定义的指针,用来存储被等待线程的返回值 返回值 : 0代表成功。 失败,返回的则是错误号。

示例代码:

#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
void * pthread_fun(void * arg) {
        printf("the arg :%d \n", (int *)arg);
        pthread_exit((void*)6666);
}

int main() {
        int id = 999;
        void * p1_id;
        pthread_t thread;
        pthread_create(&thread, NULL, pthread_fun, (void *)id);
        pthread_join(thread, &p1_id);
        printf("p1_id:%d\n", (int *)p1_id);
        printf("main thread id is %u\n",(unsigned)pthread_self());
        return 0;
}

//Compile and link with -pthread. result:the arg :999 p1_id:6666main thread id is 4155574048

二.linux 多线程的互斥锁及相关API使用:

1.pthread_mutex_init int pthread_mutex_init(pthread_mutex_t restrict mutex, const pthread_mutexattr_t restrict attr); 互斥锁的初始化。pthread_mutex_init()函数是以动态方式创建互斥锁的,参数attr指定了新建互斥锁的属性。如果参数attr为NULL,则使用默认的互斥锁属性,默认属性为快速互斥锁。互斥锁的属性在创建锁的时候指定.

2.pthread_mutex_destroy  int pthread_mutex_destroy(pthread_mutex_t *mutex); //mutex 指向要销毁的互斥锁的指针  互斥锁销毁函数在执行成功后返回 0,否则返回错误码。

3.pthread_mutex_lock 当返回时,该互斥锁已被锁定。调用线程是该互斥锁的属主。如果该互斥锁已被另一个线程锁定和拥有,则调用线程将阻塞,直到该互斥锁变为可用为止。

4.pthread_mutex_unlock 与pthread_mutex_lock成对存在。释放互斥锁

5.pthread_mutex_tylock(pthread_mutex_t *mutex);加锁,但是与3不一样的是当锁已经在使用的时候,返回为EBUSY,而不是挂起等待。

下面来看看多线程的数据同步示例:

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

typedef struct ct_sum  
{ 
    int sum;  
    pthread_mutex_t m_tMutex;  
}ct_sum;

void * add1(void * cnt) {       
    pthread_mutex_lock(&(((ct_sum*)cnt)->m_tMutex));  
    int i = 0;  
    for(i; i<50; i++)  
    {
            (*(ct_sum*)cnt).sum += i;  
    }  
    printf("add1 sum:%d\n", (*(ct_sum*)cnt).sum);
    pthread_mutex_unlock(&(((ct_sum*)cnt)->m_tMutex));  
    pthread_exit(NULL);  
    return 0;  
}  

void * add2(void *cnt) {       
    int i = 50;   
    pthread_mutex_lock(&(((ct_sum*)cnt)->m_tMutex));  
    for(i; i<101; i++)  
    {
        (*(ct_sum*)cnt).sum += i;  
    }  
    printf("add2 sum:%d\n", (*(ct_sum*)cnt).sum);
    pthread_mutex_unlock(&(((ct_sum*)cnt)->m_tMutex));  
    pthread_exit(NULL);  
    return 0;  
}  


int main(void) { 
    int i;  
    pthread_t ptid1, ptid2;  
    int sum = 0;  
    ct_sum cnt;  
    pthread_mutex_init(&(cnt.m_tMutex), NULL);  
    cnt.sum = 0;  

     pthread_create(&ptid1, NULL, add1, &cnt);  
    pthread_create(&ptid2, NULL, add2, &cnt);  

    pthread_join(ptid1, NULL);  
    pthread_join(ptid2, NULL);  

    printf("sum %d\n", cnt.sum);  
    pthread_mutex_destroy(&(cnt.m_tMutex));  
     return 0;  
}

三.linux多线程的互条件变量及相关API使用:

1.pthread_cond_init()被用来初始化一个条件变量。它的原型为:extern int pthread_cond_init P ((pthread_cond_t *cond,const pthread_condattr_t *cond_attr));其中cond是一个指向结构pthread_cond_t的指针,cond_attr是一个指向结构pthread_condattr_t的指针。结构pthread_condattr_t是条件变量的属性结构,和互斥锁一样我们可以用它来设置条件变量是进程内可用还是进程间可用, 默认值是PTHREAD_PROCESS_PRIVATE,即此条件变量被同一进程内的各个线程使用; 如果选择为PTHREAD_PROCESS_SHARED则为多个进程间各线程公用。 注意初始化条件变量只有未被使用时才能重新初始化或被释放。返回值:函数成功返回0;任何其他返回值都表示错误。

也可以静态的初始化条件变量  pthread_cond_t my_condition = PTHREAD_COND_INITIALIZER;

2.pthreadcond destroy(pthread_cond_t *cond)释放一个条件变量的函数。

3.pthread_cond_signal函数的作用是发送一个信号给另外一个正在处于阻塞等待状态的线程,使其脱离阻塞状态,继续执行.如果没有线程处在阻塞等待状态,pthread_cond_signal也会成功返回。

注意:使用pthread_cond_signal不会有“惊群现象”产生,他最多只给一个线程发信号。假如有多个线程正在阻塞等待着这个条件变量的话,那么是根据各等待线程优先级的高低确定哪个线程接收到信号开始继续执行。如果各线程优先级相同,则根据等待时间的长短来确定哪个线程获得信号。但无论如何一个pthread_cond_signal调用最多发信一次。

4.pthread_cond_wait / pthread_cond_timedwait条件变量是利用线程间共享的全局变量进行同步的一种机制,主要包括两个动作: 一个线程等待"条件变量的条件成立"而挂起; 另一个线程使"条件成立"(给出条件成立信号)。 为了防止竞争,条件变量的使用总是和一个互斥锁结合在一起。

其中pthread_cond_timedwait为计时等待,计时等待方式如果在给定时刻前条件没有满足,则返回ETIMEOUT,结束等待。无论哪种等待方式,都必须和一个互斥锁配合,以防止多个线程同时请求pthread_cond_wait()(或pthread_cond_timedwait(),下同)的竞争条件(Race Condition)。mutex互斥锁必须是普通锁(PTHREAD_MUTEX_TIMED_NP)或者适应锁(PTHREAD_MUTEX_ADAPTIVE_NP),且在调用pthread_cond_wait()前必须由本线程加锁(pthread_mutex_lock()),而在更新条件等待队列以前,mutex保持锁定状态,并在线程挂起进入等待前解锁。在条件满足从而离开pthread_cond_wait()之前,mutex将被重新加锁,以与进入pthread_cond_wait()前的加锁动作对应。

5.pthread_cleanup_push()/pthread_cleanup_pop()的相关介绍(下面的示例中将用到):线程终止有两种情况:正常终止和非正常终止。线程主动调用pthread_exit()或者从线程函数中return都将使线程正常退出,这是可预见的退出方式;非正常终止是线程在其他线程的干预下,或者由于自身运行出错(比如访问非法地址)而退出,这种退出方式是不可预见的。不论是可预见的线程终止还是异常终止,都会存在资源释放的问题,在不考虑因运行出错而退出的前提下,如何保证线程终止时能顺利的释放掉自己所占用的资源,特别是锁资源,就是一个必须考虑解决的问题。

最经常出现的情形是资源独占锁的使用:线程为了访问临界资源而为其加上锁,但在访问过程中被外界取消,如果线程处于响应取消状态,且采用异步方式响应,或者在打开独占锁以前的运行路径上存在取消点,则该临界资源将永远处于锁定状态得不到释放。外界取消操作是不可预见的,因此的确需要一个机制来简化用于资源释放的编程。

在线程API中提供了一个pthread_cleanup_push()/pthread_cleanup_pop()函数对用于自动释放资源 --从pthread_cleanup_push()的调用点到pthread_cleanup_pop()之间的程序段中的终止动作(包括调用 pthread_exit()和取消点终止)都将执行pthread_cleanup_push()所指定的清理函数。示例代码:

#include<pthread.h>
#include<unistd.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

 //这里我们采用静态初始化
static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

struct node 
{
    int n_number;
    struct node *n_next;
} *head=NULL; /*[thread_func]*/

/*释放节点内存*/
static void cleanup_handler(void*arg) {
    printf("Clean up handler of second thread.\n");
    free(arg);
    (void)pthread_mutex_unlock(&mtx);
}

static void *thread_func(void *arg) {
    struct node*p = NULL;
    pthread_cleanup_push(cleanup_handler, p);

    pthread_mutex_lock(&mtx);
    //这个mutex_lock主要是用来保护wait等待临界时期的情况,
    //当在wait为放入队列时,这时,已经存在Head条件等待激活
    //的条件,此时可能会漏掉这种处理
    //这个while要特别说明一下,单个pthread_cond_wait功能很完善,
    //为何这里要有一个while(head==NULL)呢?因为pthread_cond_wait
    //里的线程可能会被意外唤醒,如果这个时候head==NULL,
    //则不是我们想要的情况。这个时候,
    //应该让线程继续进入pthread_cond_wait
    while(1) 
    {
        while(head == NULL) 
        {
            pthread_cond_wait(&cond, &mtx);
        }
        //pthread_cond_wait会先解除之前的pthread_mutex_lock锁定的mtx,
        //然后阻塞在等待队列里休眠,直到再次被唤醒
        //(大多数情况下是等待的条件成立而被唤醒,唤醒后,
        //该进程会先锁定先pthread_mutex_lock(&mtx);,
        //再读取资源用这个流程是比较清楚的
        /*block-->unlock-->wait()return-->lock*/
        p = head;
        head = head->n_next; 
        printf("Got %d from front of queue\n", p->n_number);
        //释放主线程中申请的内存
        free(p); 
    }
    pthread_mutex_unlock(&mtx);//临界区数据操作完毕,释放互斥锁
    pthread_cleanup_pop(0);
    return 0;
}

int main(void) {
    pthread_t tid;
    int i;
    struct node *p;
    pthread_create(&tid, NULL, thread_func, NULL);
    //子线程会一直等待资源,类似生产者和消费者,
    //但是这里的消费者可以是多个消费者,
    //而不仅仅支持普通的单个消费者,这个模型虽然简单,
    //但是很强大
    for (i=0; i<10; i++) 
    {
        p = (struct node*)malloc(sizeof(struct node));
        p->n_number = i;
        pthread_mutex_lock(&mtx);//需要操作head这个临界资源,先加锁,
        p->n_next = head;
        head = p;
        pthread_cond_signal(&cond);
        pthread_mutex_unlock(&mtx);//解锁
        sleep(1);
    }
    printf("thread1 wanna end the cancel thread2.\n");
    pthread_cancel(tid);
    //关于pthread_cancel,有一点额外的说明,它是从外部终止子线程,
    //子线程会在最近的取消点,退出线程,而在我们的代码里,最近的
    //取消点肯定就是pthread_cond_wait()了。
    pthread_join(tid, NULL);
    printf("Alldone--exiting\n");
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值