上一篇文章中主要讲解了Linux环境下多线程的基本概念和特性,本文将说明Linux环境下多线程的同步方式。

  在《UNIX环境高级编程》第二版的“第11章 线程”中,提到了类UNIX系统中的三种基本的同步机制:互斥、读写锁、条件变量。下面分别针对这三种机制进行说明:

一、线程互斥

  互斥意味着具有“排它性”,即两个线程不能同时进入被互斥保护的代码。Linux下可以通过pthread_mutex_t 定义互斥体机制完成多线程的互斥操作,该机制的作用是对某个需要互斥的部分,在进入时先得到互斥体,如果没有得到互斥体,表明互斥部分被其它线程拥有,此时欲获取互斥体的线程阻塞,直到拥有该互斥体的线程完成互斥部分的操作为止。 互斥量的操作函数包括:

#include <pthread.h>
int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t, *mutexattr);
int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_unlock(pthread_mutex_t *mutex);
int pthread_mutex_destory(pthread_mutex_t *mutex);

  与其他函数一样,这些函数成功时返回0,失败时将返回错误代码,但这些函数并不设置errno,所以必须对函数的返回代码进行检查。下面以一个例子来说明用法:

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

#define SIZE 1024
char buffer[SIZE];

void *thread_function(void *arg);
pthread_mutex_t mutex;

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

    res = pthread_mutex_init(&mutex, NULL);
    if (res != 0)
    {
        perror("Mutex init failed!");
        exit(EXIT_FAILURE);
    }

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

    printf("Input some text. Enter 'end' to finish/n");

    while (1)
    {
        pthread_mutex_lock(&mutex);
        scanf("%s", buffer);
        pthread_mutex_unlock(&mutex);
        if (strncmp("end", buffer, 3) == 0)
            break;
        sleep(1);
    }

    res = pthread_join(a_thread, &thread_result);
    if (res != 0)
    {
        perror("Thread join failed!");
        exit(EXIT_FAILURE);
    }

    printf("Thread joined/n");

    pthread_mutex_destroy(&mutex);

    exit(EXIT_SUCCESS);
}

void *thread_function(void *arg)
{
    sleep(1);

    while (1)
    {
        pthread_mutex_lock(&mutex);
        printf("You input %d characters/n", strlen(buffer));
        pthread_mutex_unlock(&mutex);
        if (strncmp("end", buffer, 3) == 0)
            break;
        sleep(1);
    }
}
View Code

相关文章: