[国嵌攻略][087][多线程程序设计]

线程概念

1.线程就是轻量级的进程。

2.线程与创建它的进程共享代码段和数据段。

3.线程拥有自己独立的栈。

线程特点

线程可以和进程做相同或不同的工作,但是与进程共享资源。

线程互斥

在实际应用中,多个线程往往会访问同一个数据或资源,为避免线程之间相互影响,需要引入线程互斥机制,而互斥锁(mutex)互斥机制就是其中一种。

thread.c

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

pthread_mutex_t mutex;
int task = 0;

void *thread0();
void *thread1();

void main(){
    //创建互斥锁
    pthread_mutex_init(&mutex, NULL);
    
    //创建子线程
    pthread_t thread[2];
    
    pthread_create(&thread[0], NULL, thread0, NULL);
    pthread_create(&thread[1], NULL, thread1, NULL);
    
    //等待子线程
    pthread_join(thread[0], NULL);
    pthread_join(thread[1], NULL);
}

void *thread0(){
    //显示线程
    printf("I am thread0!
");
    
    //处理任务
    int i;
    
    for(i = 0; i < 10; i++){
        //获取互斥锁
        pthread_mutex_lock(&mutex);
        
        //处理任务
        task++;
        
        //释放互斥锁
        pthread_mutex_unlock(&mutex);
        
        //显示任务
        printf("thread0 task:%d
", task);
        
        //睡眠等待
        sleep(1);
    }
    
    //退出线程
    pthread_exit(NULL);
}

void *thread1(){
    //显示线程
    printf("I am thread1!
");
    
    //处理任务
    int i;
    
    for(i = 0; i < 10; i++){
        //获取互斥锁
        pthread_mutex_lock(&mutex);
        
        //处理任务
        task++;
        
        //释放互斥锁
        pthread_mutex_unlock(&mutex);
        
        //显示任务
        printf("thread1 task:%d
", task);
        
        //睡眠等待
        sleep(1);
    }
    
    //退出线程
    pthread_exit(NULL);
}
原文地址:https://www.cnblogs.com/d442130165/p/5228876.html