Linux 多线程编程

linux 多线程编程非常简单。

一、多线程编程的流程:

创建线程--->当前线程继续工作--->[与创建的线程同步]--->[等待创建的线程结束与返回]--->当前线程继续工作。

            --->创建的线程开始工作--->[与别的线程同步]--->退出线程并返回     

线程用的几个主要的函数。

1.线程创建函数:pthread_create(pthread_t * id,pthread_attr_t *attr,void *(*start_routine)(void*),void *arg);

   id---线程id ,线程创建成功时的返回值,用于对线程的操作。

   attr---线程属性,简单的设为NULL就可以了。

   void *(*start_routine)(void*) --- 线程函数,也就工作线程的实际运行部分的代码段。

   arg --- 线程参数,是双向的,也就是一个输入输出类型的参数。

2.等待线程返回函数:pthread_join(pthread_t id,void *ret);

   id--- 线程id。

   ret --- 线程的返回值。

3.退出线程:pthread_exit(void *ret);

   ret --- 线程返回值。

 

一个简单的线程的例子:

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

void *thread_function(void *arg);

char message[] = "Hello World";

int main() {
    int res;
    pthread_t a_thread;
    void *thread_result;
    res = pthread_create(&a_thread, NULL, thread_function, (void *)message);
    if (res != 0) {
        perror("Thread creation failed");
        exit(EXIT_FAILURE);
    }
    printf("Waiting for thread to finish.../n");
    res = pthread_join(a_thread, &thread_result);
    if (res != 0) {
        perror("Thread join failed");
        exit(EXIT_FAILURE);
    }
    printf("Thread joined, it returned %s/n", (char *)thread_result);
    printf("Message is now %s/n", message);
    exit(EXIT_SUCCESS);
}

void *thread_function(void *arg) {
    printf("thread_function is running. Argument was %s/n", (char *)arg);
    sleep(3);
    strcpy(message, "Bye!");
    pthread_exit("Thank you for the CPU time");
}

程序编译:

gcc thread1.c -o thread1 -lpthread

 

二、信号量同步

 1.创建信号量:sem_init(sem_t *sem,int pshared,unsigned int value);

    sem --- 信号量id ,用于后续对信号量的操作

    pshare --- 是否是别的进程可访问的信号量,设为0就可以。

    value --- 信号量的初始值,一般设为0 ,也就是初始状态没有信号就可以。

 2.等待信号量:sem_wait(sem_t *sem);

    sem --- 信号量id。

 3.置信号量:sem_post(sem_t *sem);    //信号量加一操作

    sem --- 信号量id。

 4.删除信号量:sem_destroy(sem_t *sme)

    sem --- 信号量id。

 使用信号量线程的例子:

 

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

void *thread_function(void *arg);
int run_now = 1;
char message[] = "Hello World";

int main() {
    int res;
    pthread_t a_thread;
    void *thread_result;
    int print_count1 = 0;

    res = pthread_create(&a_thread, NULL, thread_function, (void *)message);
    if (res != 0) {
        perror("Thread creation failed");
        exit(EXIT_FAILURE);
    }

    while(print_count1++ < 20) {
        if (run_now == 1) {
            printf("1");
            run_now = 2;
        }
        else {
            sleep(1);
        }
    }

    printf("/nWaiting for thread to finish.../n");
    res = pthread_join(a_thread, &thread_result);
    if (res != 0) {
        perror("Thread join failed");
        exit(EXIT_FAILURE);
    }
    printf("Thread joined/n");
    exit(EXIT_SUCCESS);
}

void *thread_function(void *arg) {
    int print_count2 = 0;

    while(print_count2++ < 20) {
        if (run_now == 2) {
            printf("2");
            run_now = 1;
        }
        else {
            sleep(1);
        }
    }

    sleep(3);
}

 

三、使用互斥量同步线程:

 

二、信号量同步

 1.创建互斥量:phread_mutex_init(phread_mutex_t *mutex,const pthread_mutexattr_t *mutexattr);

    mutex--- 互斥量id ,用于后续对互斥量的操作

    mutexattr --- 互斥量属性,一般的用默认置,设为NULL就可以了。

 2.互斥量加锁:phread_mutex_lock(phread_mutex_t *mutex);

    mutex--- 信号量id。

 3.互斥量解锁:phread_mutex_unlock(phread_mutex_t *mutex);    

    mutex--- 信号量id。

 4.删除互斥量:phread_mutex_destroy(phread_mutex_t *mutex)

    mutex--- 信号量id。

 

 使用互斥量线程的例子:

 

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

void *thread_function(void *arg);
pthread_mutex_t work_mutex; /* protects both work_area and time_to_exit */

#define WORK_SIZE 1024
char work_area[WORK_SIZE];
int time_to_exit = 0;

int main() {
    int res;
    pthread_t a_thread;
    void *thread_result;
    res = pthread_mutex_init(&work_mutex, NULL);
    if (res != 0) {
        perror("Mutex initialization failed");
        exit(EXIT_FAILURE);
    }
    res = pthread_create(&a_thread, NULL, thread_function, NULL);
    if (res != 0) {
        perror("Thread creation failed");
        exit(EXIT_FAILURE);
    }
    pthread_mutex_lock(&work_mutex);
    printf("Input some text. Enter 'end' to finish/n");
    while(!time_to_exit) {
        fgets(work_area, WORK_SIZE, stdin);
        pthread_mutex_unlock(&work_mutex);
        while(1) {
            pthread_mutex_lock(&work_mutex);
            if (work_area[0] != '/0') {
                pthread_mutex_unlock(&work_mutex);
                sleep(1);
            }
            else {
                break;
            }
        }
    }
    pthread_mutex_unlock(&work_mutex);
    printf("/nWaiting for thread to finish.../n");
    res = pthread_join(a_thread, &thread_result);
    if (res != 0) {
        perror("Thread join failed");
        exit(EXIT_FAILURE);
    }
    printf("Thread joined/n");
    pthread_mutex_destroy(&work_mutex);
    exit(EXIT_SUCCESS);
}

void *thread_function(void *arg) {
    sleep(1);
    pthread_mutex_lock(&work_mutex);
    while(strncmp("end", work_area, 3) != 0) {
        printf("You input %d characters/n", strlen(work_area) -1);
        work_area[0] = '/0';
        pthread_mutex_unlock(&work_mutex);
        sleep(1);
        pthread_mutex_lock(&work_mutex);
        while (work_area[0] == '/0' ) {
            pthread_mutex_unlock(&work_mutex);
            sleep(1);
            pthread_mutex_lock(&work_mutex);
        }
    }
    time_to_exit = 1;
    work_area[0] = '/0';
    pthread_mutex_unlock(&work_mutex);
    pthread_exit(0);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值