Linux 多线程Posix详解(二) : 线程的同步与互斥

Posix多线程系列文章:
Linux 多线程Posix详解(一) : 线程的创建、等待、退出、取消与清理
Linux 多线程Posix详解(二) : 线程的同步与互斥
Linux 多线程Posix详解(三) : C++封装


一.线程互斥

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) throw()

互斥锁的使用形式如下:

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_lock(&mutex);
//doing …
pthread_mutex_unlock(&mutex);

mutex我们用得最多的就是互斥锁,用来对公共资源进行加锁(实质上在操作中是对某个线程加锁,然后只有加锁之后的线程才能访问公共资源),这样便可以实现了对多线程的互斥访问。

所谓的锁(即mutex),只是一种形式,只有再加锁后,释放前,才能够对公共资源进行操作。对于一个公共资源,我们通常使用一把锁,如果是多个公共资源那么就需要多把锁。

案例:主线程与子线程各加一千万

在没有使用互斥锁的情况下,主线程与子线程相加一千万是小于两千万的,使用互斥锁,那么结果便等于两千万
另外,与两个进程相加一千万对比,多线程很明显更加迅速。

int N = 10000000;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *threadFunc(void *arg)
{
    for (int i = 0; i < N; i++)
    {
        pthread_mutex_lock(&mutex);
        *(int *)arg += 1;
        pthread_mutex_unlock(&mutex);
    }
    pthread_exit(NULL);
}

int main()
{
    int sum = 0;
    pthread_t pid;
    pthread_create(&pid, NULL, threadFunc, &sum);
    for (int i = 0; i < N; i++)
    {
        pthread_mutex_lock(&mutex);
        sum++;
        pthread_mutex_unlock(&mutex);
    }
    pthread_join(pid, NULL);
    cout << "final sum = " << sum << endl;
    return 0;
}

二.线程同步

int pthread_cond_init(pthread_cond_t *__restrict__ __cond, const pthread_condattr_t *__restrict__ __cond_attr)

int pthread_cond_wait(pthread_cond_t *__restrict__ __cond, pthread_mutex_t *__restrict__ __mutex)

int pthread_cond_signal(pthread_cond_t *__cond)

其中条件等待的过程十分重要,下面来看看流程。
pthread_cond_wait的实现:

  • 1.必须先pthread_mutex_lock进行加锁
  • 2.进入pthread_cond_wait之后,将该线程加入内核的等待队列之后,释放锁
  • 3.等待pthread_cond_signal唤醒之后,内核会给线程加锁;
  • 4.此时一般进行while条件判断:
    1):情况满足则 执行execute语句之后再pthread_mutex_unlock解锁
    2):情况不满足则 再次重复执行pthread_cond_wait

用代码的形式体现就是:

while (1){
    pthread_mutex_lock(&mutex);
    while (condition){
        pthread_cond_wait(&cond,&mutex);
    }
    //execute work
    ...
    pthread_mutex_unlock(&mutex);
}

从代码上面看,cond其实也就只是加了一个条件判断语句,用来判断条件是否满足才开始执行。

问题:
1.为什么while()循环之前必须加锁?
1):必须先抢锁,再判断!
2):pthread_cond_wait内部会解锁,所以再之前必须加锁!

2.while循环可以换成if循环吗?
不行,因为有可能用signal唤醒的是多个等待的线程,可能有的线程已经不满足条件了,所以必须循环判断,满足条件的才能执行下面的execute语句

总的来说,cond条件变量的作用 就是在不断的判断一个条件是否满足,满足之后才能执行execute。

通过以下测试用例可以大概了解线程同步的过程
测试用例(一):条件等待

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void* threadFunc(void* arg)
{
    cout << "child thread "  << (long)arg << " is running and try to get the mutex " << endl;
    pthread_mutex_lock(&mutex);
    cout << "child thread " << (long)arg << " release the mutex and joined the waited_queue to wait for pthread_cond_signal" << endl;
    pthread_cond_wait(&cond, &mutex);
    cout << "child thread " << (long)arg << " get the mutex , then doing things" << endl;
    pthread_mutex_unlock(&mutex);    

    pthread_exit(NULL);
}

const long N = 100;
int main()
{
    pthread_t pids[N];
    for (long i = 0; i < N; i++)
        pthread_create(&pids[i], NULL, threadFunc, (void*)i);
    sleep(1);

    for (long i = 0; i < N; i++)
    {
        pthread_cond_signal(&cond);
        // sleep(1);
    }

    for (long i = 0; i < N; i ++)
        pthread_join(pids[i], NULL);
    return 0;
}

测试用例(二):限时条件等待

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void* threadFunc(void* arg)
{
    cout << "child thread "  << (long)arg << " is running and try to get the mutex " << endl;
    pthread_mutex_lock(&mutex);
    cout << "child thread " << (long)arg << " release the mutex and joined the waited_queue to wait for pthread_cond_signal" << endl;
    struct timespec tv;
    tv.tv_sec = time(NULL) + 5; //必须加上 time(NULL)
    tv.tv_nsec = 0;
    pthread_cond_timedwait(&cond, &mutex, &tv); 
    int ret = pthread_mutex_unlock(&mutex);    
    cout << ret << endl;
    cout << "timeout and leave" << endl;

    pthread_exit(NULL);
}

const long N = 3;
int main()
{
    pthread_t pids[N];
    for (long i = 0; i < N; i++)
        pthread_create(&pids[i], NULL, threadFunc, (void*)i);
    sleep(1);

    for (long i = 0; i < N; i ++)
        pthread_join(pids[i], NULL);
    return 0;
}

案例:窗口卖票程序(也可以说是生产者消费者案例:两个消费者,一个生产者)

创建两个子线程卖票,第三个子线程放票,两个子线程卖完20张票后,
第三个子线程把票重新设置为20,然后两个子线程继续卖票,把票卖光

#define N 20
struct Train
{
    int tickets;
    pthread_cond_t cond;
    pthread_mutex_t mutex;
} train;

typedef void *(*Func)(void *);

void *sell_window1(void *arg)
{
    Train *train = (Train *)arg;
    while (1)
    {
        pthread_mutex_lock(&train->mutex);
        while (train->tickets == 0)
            pthread_cond_wait(&train->cond, &train->mutex);
        train->tickets--;
        cout << "window1 sell 1 ticket, there are " << train->tickets << " left " << endl;
        pthread_mutex_unlock(&train->mutex);
        sleep(1);
    }
}

void *sell_window2(void *arg)
{
    Train *train = (Train *)arg;
    while (1)
    {
        pthread_mutex_lock(&train->mutex);
        while (train->tickets == 0)
            pthread_cond_wait(&train->cond, &train->mutex);
        train->tickets--;
        cout << "window2 sell 1 ticket, there are " << train->tickets << " left " << endl;
        pthread_mutex_unlock(&train->mutex);
        sleep(1);
    }
}

void *set_tickets(void *arg)
{
    Train *train = (Train *)arg;
    while (1)
    {
        pthread_mutex_lock(&train->mutex);
        if (train->tickets == 0)
        {
            train->tickets = 20;
            cout << "reset 20 tickets" << endl;
            pthread_cond_signal(&train->cond);
        }
        pthread_mutex_unlock(&train->mutex);
    }
}

int main()
{
    train.tickets = N;
    train.cond = PTHREAD_COND_INITIALIZER;
    train.mutex = PTHREAD_MUTEX_INITIALIZER;
    Func threadFuncs[3] = {sell_window1, sell_window2, set_tickets};
    pthread_t pids[3];
    for (int i = 0; i < 3; i++)
        pthread_create(&pids[i], NULL, threadFuncs[i], &train);

    for (int i = 0; i < 3; i++)
        pthread_join(pids[i], NULL);

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值