线程控制(一)

1. 线程执行顺序问题

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

void *thread1(void *);
void *thread2(void *);

pthread_key_t key;

void *thread1(void *arg){
    int a = 1, *tsd = &a;
    pthread_t thid2;

    printf("thread1 %lu is running\n", pthread_self());
    pthread_setspecific(key, tsd);
    pthread_create(&thid2, NULL, thread2, NULL);
    sleep(3);  //---2
    tsd = (int *)pthread_getspecific(key);
    printf("thread1 %lu returns %d\n", pthread_self(), *tsd);

    return (void *)0;
}

void *thread2(void *arg){
    int a = 5, *tsd = &a;
    printf("thread2 %lu is running\n", pthread_self());
    pthread_setspecific(key, (int *)tsd);
    tsd = (int *)pthread_getspecific(key);
    printf("thread2 %lu returns %d\n", pthread_self(), *tsd);//tsd is a pointer

    return (void *)0;
}

int main(int argc, char const *argv[])
{
    pthread_t thid1;

    printf("main thread is running\n");
    pthread_key_create(&key, NULL);
    pthread_create(&thid1, NULL, thread1, NULL);
    sleep(5);  //---1
    pthread_key_delete(key);
    printf("main thread exit\n");

    return 0;
}

1)代码1、2处都不注释,运行结果:

 test1

2)代码中2处注释掉,1保留,运行结果:

 est2

3)代码中1处注释掉,2保留,运行结果:

test3


奇怪的现象发生了!!

我们会发现,在第3种情况中,竟然只有main函数中的内容输出了,而子线程好像没有运行。为什么呢?原来,在用户没有设定线程间的调度策略时,系统默认采取基于时间片轮转的调度策略。此时,子线程要在主线程空闲的条件下才会执行,假设主线程一直在工作,那么子线程没有机会运行,直到主线程退出。

然而,由于线程间共享资源,主线程的退出会影响到该进程下的所有线程,所以子线程就永远没有机会执行,也就造成了第3种只有main函数中的内容输出了。

而使用sleep函数会让程序挂起一段时间,让子进程得到运行的机会,所以前两种情况所有函数中内容都有输出,只是顺序不同而已。当然,子线程的执行顺序也是不确定的,这就要看操作系统的具体分配了。


2. 条件变量的使用

int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex);
pthread_cond_signal(pthread_cond_t *cond);

pthread_cond_wait会先解锁mutex指向的互斥锁,再将cond指向的条件变量阻塞,直到该条件变量值改变,再将mutex指向的互斥锁加锁。

pthread_cond_signal则用来激活一个正在等待条件成立的线程,使该线程继续运行。与pthread_cond_wait函数配合使用。

使用pthread_cond_wait方式如下:

pthread _mutex_lock(&mutex)
while(线程执行的条件是否成立)
      pthread_cond_wait(&cond, &mutex);
线程执行
pthread_mutex_unlock(&mutex);

为什么要在while内判断呢?

因为在等待运行的程序会有很多,所以需要竞争才能得到下一次运行的权利,而在pthread_cond_signal或者pthread_cond_broadcast执行后,wait虽然成功了,但是当前线程不一定就能竞争到运行的权利,可能被其他更加“强大”的线程抢到手,所以需要不断循环来判断是达到了可以执行的条件。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值