• POSIX线程-(四)


    使用互斥同步

    在多线程程序中同步访问的另一个方法就是使用互斥,其作用允许程序锁住一个对象,从而只有一个线程可以访问他。要控制对临界区代码的访问,在我们进入这段代码之前锁住一个互斥量,并且在我们完成操作时进行解锁。

    使用互斥所需要基本函数与信号量所需要的函数相似,其声明如下:

    #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_destroy(pthread_mutex_t *mutex);

    如平常一样,成功时返回0,如果失败则会返回一个错误代码,但是并没有设置errno;我们必须使用返回代码。

    与信号量相类似,这些函数以一个指向前面声明的对象的指针为参数,在互斥方法是一个pthread_mutex_t。额外的属性参数pthread_mutexattr_t允许我们为互斥提供属性,这可以控制其行为。属性类型默认为"fast"。这有一个小的缺点,如果我们的程序试着在一个已经上锁的互斥量上调用pthread_mutex_lock,程序就会阻塞。因为拥有锁的线程现在被阻塞了,互斥量就不会被解锁,从而程序就会进入死锁状态。可以修改互斥量的属性,从而他或者可以检测这种情况并返回一个错误,或者是循环操作并且在同一个线程上允许多个锁。

    设置互斥量的属性超出了本书的范围,所以我们会为属性指针传递NULL并且使用默认行为。我们可以通过阅读pthread_mutex_init手册页了解修改属性的内容。

    试验--线程互斥

    再一次说明,下面的程序是我们原始程序thread1.c的修改版,但是进行了大量的修改。这一次,我们有一些偏狂来访问我们的临界变量,并且使用一个互斥量来保证每次只有一个线程访问他们。为了使得代码更易于阅读,我们忽略了由互斥量加锁与解锁操作返回值的错误检测。在生产代码中,我们应该检测这些返回值。下面是这个新程序,thread4.c:

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

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

    #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);
    }

    $ cc -D_REENTRANT -I/usr/include/nptl thread4.c –o thread4 -L/usr/lib/nptl -
    lpthread
    $ ./thread4
    Input some text. Enter ‘end’ to finish
    Whit
    You input 4 characters
    The Crow Road
    You input 13 characters
    end
    Waiting for thread to finish...
    Thread joined

    工作原理

    我们开始声明了一个互斥量,我们的工作区,而且这次,我们声明了一个额外变量:time_to_exit。

    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;

    然后我们初始化互斥量

    res = pthread_mutex_init(&work_mutex, NULL);
    if (res != 0) {
        perror(“Mutex initialization failed”);
        exit(EXIT_FAILURE);
    }

    接下来我们开始我们的新线程。下面是线程函数内部执行的代码:

    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);

    首先,新线程尝试锁住这个互斥量。如果他已经被锁住了,调用就会阻塞直到互斥量被释放。一旦我们访问,我们进行检测来查看我们是否正被请求退出。如果我们被请求退出,我们只是简单的设置time_to_exit,清除工作区的第一个字符,并且退出。

    如果我们不希望退出,我们计算字符数然后清空第一个字符为空。我们使用将第一个字符清空的方法来通知读取程序我们已经完成了计算。我们然后解锁互斥量并且等待主线程运行。我们会循环尝试锁住这个互斥量,当我们成功时,我们会检测主线程是否为我们指定了更多的工作要做。如果没有,我们解锁互斥量并等待一段更长的时间。如果有,我们计算字符数并且再次进入循环。

    下面是主线程:

    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);

    这与上面所说的线程类似。我们锁住工作区域,从而我们可以向其中读取文本,然后解锁允许其他的线程访问来计算单词数。循环往复,我们重新锁住互斥量,检测单词数是否进行了计算,如果我们需要等待更长的时间,我们就会释放这个锁。正如我们在前面所注意到的,这并不是一个好的编程习惯,而在真实的世界中,我们可以使用信号量来避免这种情况。然而,这里的代码只是作为一个例子。

  • 相关阅读:
    苹果手机 iframe 无法滚动bug
    网页实现文件下载的一些方法
    Document对象中的一些重要的属性和方法(笔记)
    window对象中的一些重要的属性和方法(笔记)
    JS中的继承
    利用XMLHttpRequest(XHR)对象实现与web服务器通信
    JS对象中的原型
    JS中this的指向
    JS中的作用域和闭包
    HTML5新增的本地存储功能(笔记)
  • 原文地址:https://www.cnblogs.com/dyllove98/p/2461948.html
Copyright © 2020-2023  润新知