Unix 环境高级编程---线程创建、同步、
一下代码主要实现了linux下线程创建的基本方法,这些都是使用默认属性的。以后有机会再探讨自定义属性的情况。主要是为了练习三种基本的线程同步方法:互斥、读写锁以及条件变量。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h> int g_count = ;
pthread_mutex_t mutex_lock;
pthread_rwlock_t rw_lock;
pthread_cond_t con_val = PTHREAD_COND_INITIALIZER; typedef enum
{
MutexLock = ,
RWLock,
CondLock
}LockType; typedef struct
{
int val;
LockType type;
}ThreadData; void PrintThreadId()
{
pid_t pid;
pthread_t tid; pid = getpid();
tid = pthread_self(); printf("[%s] process id : %d thread id : 0x%lx\n",__func__,pid,tid);
} void CleanUpFun(void *arg)
{ printf("[%s] clean up : %s \n",__func__,(char *)arg);
} void AddCount(int tid,LockType type)
{
if(type == MutexLock)
{
printf("[%s] thread %d MutexLock the count is : %d\n",__func__,tid,g_count);
pthread_mutex_lock(&mutex_lock);
while(g_count < )
{
usleep();
printf("%d-%d \t",tid,g_count);
g_count++;
}
printf("\n");
pthread_mutex_unlock(&mutex_lock);
} if(type == RWLock)
{
pthread_rwlock_wrlock(&rw_lock);
printf("[%s] thread %d RWLock the count is : %d\n",__func__,tid,g_count);
while(g_count < )
{
usleep();
printf("%d-%d \t",tid,g_count);
g_count++;
}
printf("\n");
pthread_rwlock_unlock(&rw_lock); } if(type == CondLock)
{
printf("[%s] thread %d CondLock the count is : %d\n",__func__,tid,g_count);
pthread_mutex_lock(&mutex_lock); g_count = ;
printf("[%s] thread %d CondLock the count is : %d\n",__func__,tid,g_count); pthread_mutex_unlock(&mutex_lock); pthread_cond_signal(&con_val);
} } void DelCount(int tid,LockType type)
{
usleep(); if(type == MutexLock)
{
pthread_mutex_lock(&mutex_lock); printf("[%s] thread %d MutexLock the count is : %d\n",__func__,tid,g_count);
while(g_count > )
{
usleep();
printf("%d-%d \t",tid,g_count);
g_count--;
}
printf("\n");
pthread_mutex_unlock(&mutex_lock);
} if(type == RWLock)
{
pthread_rwlock_wrlock(&rw_lock); printf("[%s] thread %d RWLock the count is : %d\n",__func__,tid,g_count);
while(g_count > )
{
usleep();
printf("%d-%d \t",tid,g_count);
g_count--;
}
printf("\n");
pthread_rwlock_unlock(&rw_lock); } if(type == CondLock)
{
pthread_mutex_lock(&mutex_lock); // printf("[%s] thread %d CondLock the count is : %d\n",__func__,tid,g_count); //while(1)
{
pthread_cond_wait(&con_val,&mutex_lock); printf("[%s] thread %d CondLock the count is : %d\n",__func__,tid,g_count);
} pthread_mutex_unlock(&mutex_lock);
} } void PrintCount(int tid,LockType type)
{
if(type == RWLock)
{
pthread_rwlock_rdlock(&rw_lock); printf("[%s] thread %d RWLock the count is : %d\n",__func__,tid,g_count); pthread_rwlock_unlock(&rw_lock);
}
else
{ } } void ChangCount(int tid,LockType type)
{ if((tid == ) || (tid == ))
{
AddCount(tid,type);
}
else if((tid == ))
{
DelCount(tid,type);
}
else if(tid == )
{
PrintCount(tid,type);
} } void * ThreadFun(ThreadData *t)
{
printf("\n----------------------------------------------------------\n"); int val = ;
LockType type = ;
val = t->val;
type = t->type; printf("[%s] this is thread %d\n",__func__,val);
PrintThreadId(); char buf[];
sprintf(buf,"thread %d first handler ",val);
pthread_cleanup_push(CleanUpFun,buf);/*push and pop must be coupled*/ int len = strlen(buf);
sprintf(buf+len+,"thread %d second handler ",val);/*Notice !!! */
pthread_cleanup_push(CleanUpFun,buf+len+);/*the buf must start from different address , to the cleanupfunc ,the poniter is the same !!!*/ ChangCount(val,type); if(val == )
{
printf("----------------------------------------------------------\n");
return ((void *)val);/*clean up func won't run*/
}
else
{
printf("----------------------------------------------------------\n");
pthread_exit((void *)val);/*clean up func won run*/
}
pthread_cleanup_pop();
pthread_cleanup_pop(); return ((void *)val);
} void JoinThread(pthread_t tid)
{
void * ret; int err; err = pthread_join(tid,&ret); if(err != )
{
printf("error to join thread %lu\n",tid);
} printf("\n[%s] catch thread 0x%lx , the return val is %d\n",__func__,tid,(int)ret);
} void CreateThread(LockType type)
{
int err; ThreadData t1;
ThreadData t2;
ThreadData t3; t1.val = ;
t2.val = ;
t3.val = ; pthread_t tid_1;
pthread_t tid_2;
pthread_t tid_3; if(type == MutexLock)
{
/*Mutex lock*/
t1.type = MutexLock;
t2.type = MutexLock;
t3.type = MutexLock; err = pthread_create(&tid_1,NULL,(void *)ThreadFun,(void *)&t1);
if(err != )
{
printf("error to create thread !\n");
} err = pthread_create(&tid_2,NULL,(void *)ThreadFun,(void *)&t2);
if(err != )
{
printf("error to create thread !\n");
} JoinThread(tid_1);
JoinThread(tid_2); }
else if(type == RWLock)
{
/*rw lock*/
t1.type = RWLock;
t2.type = RWLock;
t3.type = RWLock; err = pthread_create(&tid_1,NULL,(void *)ThreadFun,(void *)&t1);
if(err != )
{
printf("error to create thread !\n");
} err = pthread_create(&tid_2,NULL,(void *)ThreadFun,(void *)&t2);
if(err != )
{
printf("error to create thread !\n");
} err = pthread_create(&tid_3,NULL,(void *)ThreadFun,(void *)&t3);
if(err != )
{
printf("error to create thread !\n");
}
JoinThread(tid_1);
JoinThread(tid_2);
JoinThread(tid_3);
}
else if(type == CondLock)
{
t1.type = CondLock;
err = pthread_create(&tid_1,NULL,(void *)ThreadFun,(void *)&t1);
if(err != )
{
printf("error to create thread !\n");
} sleep();
t2.type = CondLock;
err = pthread_create(&tid_2,NULL,(void *)ThreadFun,(void *)&t2);
if(err != )
{
printf("error to create thread !\n");
}
JoinThread(tid_1);
JoinThread(tid_2); } } void InitMutexLock()
{
if(pthread_mutex_init(&mutex_lock,NULL) != )
{
printf("[Main] error to init mutex lock\n");
}
} void DestoryMutexLock()
{
if(pthread_mutex_destroy(&mutex_lock) != )
{
printf("[Main] error to destory mutex lock\n");
}
} void DestoryRWLock()
{
if(pthread_rwlock_destroy(&rw_lock) != )
{
printf("[Main] error to destroy rw lock \n");
} } void InitRWLock()
{
if(pthread_rwlock_init(&rw_lock,NULL) != )
{
printf("[Main] error to init rw lock\n");
}
} int main(int argc,char **argv)
{
printf("=====================================mutex lock=====================================\n"); InitMutexLock(); CreateThread(MutexLock); DestoryMutexLock(); printf("=====================================rw lock=====================================\n"); InitRWLock(); CreateThread(RWLock); DestoryRWLock(); printf("=====================================Cond lock=====================================\n"); InitMutexLock(); CreateThread(CondLock); DestoryMutexLock();
printf("[Main] quit\n"); return ;
}
运行效果如下:
tiger@ubuntu:/mnt/hgfs/e/Lessons/MyExercise/UtilLibs/THREAD$ ./thread
=====================================mutex lock===================================== ----------------------------------------------------------
[ThreadFun] this is thread
[PrintThreadId] process id : thread id : 0xb6f54b70
[AddCount] thread MutexLock the count is : ----------------------------------------------------------
[ThreadFun] this is thread
[PrintThreadId] process id : thread id : 0xb7755b70
- - - - - - - - - -
----------------------------------------------------------
[DelCount] thread MutexLock the count is :
- [CleanUpFun] clean up : thread second handler
[CleanUpFun] clean up : thread first handler
- - - - - - - - -
---------------------------------------------------------- [JoinThread] catch thread 0xb7755b70 , the return val is [JoinThread] catch thread 0xb6f54b70 , the return val is
=====================================rw lock===================================== ----------------------------------------------------------
[ThreadFun] this is thread
[PrintThreadId] process id : thread id : 0xb6753b70
[PrintCount] thread RWLock the count is :
----------------------------------------------------------
[CleanUpFun] clean up : thread second handler
[CleanUpFun] clean up : thread first handler ----------------------------------------------------------
[ThreadFun] this is thread
[PrintThreadId] process id : thread id : 0xb7755b70
[AddCount] thread RWLock the count is : ----------------------------------------------------------
[ThreadFun] this is thread
[PrintThreadId] process id : thread id : 0xb6f54b70
- - - - - - - - - -
----------------------------------------------------------
[CleanUpFun] clean up : thread second handler
[CleanUpFun] clean up : thread first handler
[DelCount] thread RWLock the count is :
- - - - - - - - - -
---------------------------------------------------------- [JoinThread] catch thread 0xb6f54b70 , the return val is [JoinThread] catch thread 0xb7755b70 , the return val is [JoinThread] catch thread 0xb6753b70 , the return val is
=====================================Cond lock===================================== ----------------------------------------------------------
[ThreadFun] this is thread
[PrintThreadId] process id : thread id : 0xb6753b70 ----------------------------------------------------------
[ThreadFun] this is thread
[PrintThreadId] process id : thread id : 0xb7755b70
[AddCount] thread CondLock the count is :
[AddCount] thread CondLock the count is :
[DelCount] thread CondLock the count is :
---------------------------------------------------------- [JoinThread] catch thread 0xb6753b70 , the return val is
----------------------------------------------------------
[CleanUpFun] clean up : thread second handler
[CleanUpFun] clean up : thread first handler [JoinThread] catch thread 0xb7755b70 , the return val is
[Main] quit
tiger@ubuntu:/mnt/hgfs/e/Lessons/MyExercise/UtilLibs/THREAD$
代码相当拙劣基础,欢迎拍砖。
Unix 环境高级编程---线程创建、同步、的更多相关文章
- UNIX环境高级编程——线程属性
pthread_attr_t 的缺省属性值 属性 值 结果 scope PTHREAD_SCOPE_PROCESS 新线程与进程中的其他线程发生竞争. detachstate PTHREAD_CREA ...
- UNIX环境高级编程——线程
线程包含了表示进程内执行环境必需的信息,其中包括进程中标示线程的线程ID.一组寄存器值.栈.调度优先级和策略.信号屏蔽字.errno变量以及线程私有数据. 进程的所有信息对该进程的所有线程都是共享的, ...
- UNIX环境高级编程——线程同步之互斥锁、读写锁和条件变量(小结)
一.使用互斥锁 1.初始化互斥量 pthread_mutex_t mutex =PTHREAD_MUTEX_INITIALIZER;//静态初始化互斥量 int pthread_mutex_init( ...
- UNIX环境高级编程——线程同步之条件变量以及属性
条件变量变量也是出自POSIX线程标准,另一种线程同步机制.主要用来等待某个条件的发生.可以用来同步同一进程中的各个线程.当然如果一个条件变量存放在多个进程共享的某个内存区中,那么还可以通过条件变量来 ...
- UNIX环境高级编程——线程同步之读写锁以及属性
读写锁和互斥量(互斥锁)很类似,是另一种线程同步机制,但不属于POSIX标准,可以用来同步同一进程中的各个线程.当然如果一个读写锁存放在多个进程共享的某个内存区中,那么还可以用来进行进程间的同步, 互 ...
- UNIX环境高级编程——线程同步之互斥量
互斥量(也称为互斥锁)出自POSIX线程标准,可以用来同步同一进程中的各个线程.当然如果一个互斥量存放在多个进程共享的某个内存区中,那么还可以通过互斥量来进行进程间的同步. 互斥量,从字面上就可以知道 ...
- UNIX环境高级编程——线程和fork
当线程调用fork时,就为子进程创建了整个进程地址空间的副本.子进程通过继承整个地址空间的副本,也从父进程那里继承了所有互斥量.读写锁和条件变量的状态.如果父进程包含多个线程,子进程在fork返回以后 ...
- UNIX环境高级编程——线程私有数据
线程私有数据(Thread-specific data,TSD):存储和查询与某个线程相关数据的一种机制. 在进程内的所有线程都共享相同的地址空间,即意味着任何声明为静态或外部变量,或在进程堆声明的变 ...
- UNIX环境高级编程——线程属性之分离属性
说到线程的分离状态,我认为,之所以会有这个状态,是因为系统对某些线程的终止状态根本不感兴趣导致的. 我们知道,进程中的线程可以调用: int pthread_join(pthread_t tid, v ...
随机推荐
- Qt Linguist介绍
简介 Qt提供了一款优秀的支持Qt C++和Qt Quick应用程序的翻译工具.发布者.翻译者和开发者可以使用这款工具来完成他们的任务. 发布者:承担了全面发布应用程序的责任.通常,他们协调开发者和翻 ...
- 【转】Java之 内存区域和GC机制
转自:Leo Chin 目录 Java垃圾回收概况 Java内存区域 Java对象的访问方式 Java内存分配机制 Java GC机制 垃圾收集器 Java垃圾回收概况 Java GC(Garbage ...
- 通过javascript把图片转化为字符画
1.获取上传图片对象数据 Javascript无法直接获取本地上传的图片的数据,html5可以解决这一问题 .html5里面的FileReader interface可以把图片对象的数据读到内存,然后 ...
- 解决Eclipse快捷键被其他软件占用
做为一个java攻城狮,eclipse是我最常用的攻城设备,eclipse快捷键 极大的提高了我的开发效率!!!! 前段时间升级了一下我的战斗装备——给电脑的系统盘换成了一个固态硬盘,因此需要重装系统 ...
- Linux技巧:一次删除一百万个文件最快方法
昨天,我看到一个非常有趣的删除一个目录下的海量文件的方法.这个方法来自http://www.quora.com/How-can-someone-rapidly-delete-400-000-files ...
- Android 高仿UC浏览器监控剪切板弹出悬浮窗功能
UC浏览器应该是android手机里 最流行的浏览器之一了,他们有一个功能 相信大家都体验过,就是如果你复制了什么文字,(在其他app中 复制也有这个效果!,所以能猜到肯定是监控了剪切板),就会弹出一 ...
- IOS OC声明变量在@interface括号中与使用@property的区别(转载)
刚开始接触OC再看别人写的代码的时候,常常困惑于人家在声明属性时的写法,总结出来有三中方式,不知道哪一种比较规范化,现在我把三种方式贴出来,然后再一一探讨每个方式声明属性的区别. 方式一:直接在@in ...
- Java正确转换html编码
Java 中能將 html 編碼正確轉換的套件: org.apache.commons.lang.StringEscapeUtils. String source = "The less t ...
- git/github初级运用自如(zz)
----//git/github环境配置 一 . github上创建立一个项目 用户登录后系统,在github首页,点击页面右下角“New Repository” 填写项目信息: project n ...
- 基数排序/Go实现
package main import ( "fmt" ) type Radix struct { length int //序列中最大数的位数 radix [][]int //0 ...