• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

cynchanpin

  • 博客园
  • 联系
  • 订阅
  • 管理

View Post

linux 多线程那点事

说明:对多线程与相互排斥锁不熟悉的请參考其他


#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;/*初始化相互排斥锁*/
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;/*初始化条件变量*/
void *thread1(void *);
void *thread2(void *);
int i=1;
int main(void)
{
    pthread_t t_a;
    pthread_t t_b;
    pthread_create(&t_a,NULL,thread1,(void *)NULL);/*创建进程t_a*/
    pthread_create(&t_b,NULL,thread2,(void *)NULL); /*创建进程t_b*/
    pthread_join(t_a, NULL);/*等待进程t_a结束 和windows的waitForSingleObject 相似*/
    pthread_join(t_b, NULL);/*等待进程t_b结束 和windows的waitForSingleObject 相似*/
    /* 释放资源*/
    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);
    exit(0);
}
void *thread1(void *junk)
{
    for(i=1;i<=6;i++)
    {
	printf("now i = %d\n", i);
        pthread_mutex_lock(&mutex);/*锁住相互排斥量*/
		printf("thread1: lock %d\n", __LINE__);
        if(i%3==0){
			printf("thread1:signal 1  %d\n", __LINE__);
            pthread_cond_signal(&cond);/*条件改变,发送信号,通知t_b进程*/
			printf("thread1:signal 2  %d\n", __LINE__);
			sleep(1);
		}
        pthread_mutex_unlock(&mutex);/*解锁相互排斥量*/
		printf("thread1: unlock %d\n\n", __LINE__);
		sleep(1);
	}
}
void *thread2(void *junk)
{
    while(i<6)
    {
        pthread_mutex_lock(&mutex);
		printf("thread2: lock %d\n", __LINE__);
		if(i%3!=0){
			printf("thread2: wait 1  %d\n", __LINE__);
	    /*pthread_cond_wait 函数将解锁mutex。并使当前线程堵塞在cond指向的条件变量上*/	
            pthread_cond_wait(&cond,&mutex);/*解锁mutex,并等待cond改变*/
			printf("thread2: wait 2  %d\n", __LINE__);;
		}
        pthread_mutex_unlock(&mutex);
		printf("thread2: unlock %d\n\n", __LINE__);
		sleep(1);
	}
}



root@ubuntu:/usr/syw/linux/Thread# gcc -g threadDemo3_arg.c -o thread3 -lpthread

root@ubuntu:/usr/syw/linux/Thread# ./thread3


now i = 1
thread2: lock 44
thread2: wait 1  46
thread1: lock 27
thread1: unlock 35

now i = 2
thread1: lock 27
thread1: unlock 35

now i = 3
thread1: lock 27
thread1:signal 1  29
thread1:signal 2  31
thread1: unlock 35

thread2: wait 2  49
thread2: unlock 52

now i = 4
thread2: lock 44
thread2: wait 1  46
thread1: lock 27
thread1: unlock 35

now i = 5
thread1: lock 27
thread1: unlock 35

now i = 6
thread1: lock 27
thread1:signal 1  29
thread1:signal 2  31
thread1: unlock 35

thread2: wait 2  49
thread2: unlock 52


posted on 2017-07-28 13:24  cynchanpin  阅读(146)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3