Linux下多线程编程简介(三)
作者 佚名技术
来源 Linux系统
浏览
发布时间 2012-04-28
一个进程中的多个线程是共享同一段资源的,![]() ![]() #include <stdio.h> #include <pthread.h> #include <errno.h> #define return_if_fail(p) if(!p) { printf("[%s]:func error!", __func__); return; } typedef struct _PrivInfo { pthread_mutex_t mutex; int lock_var; time_t end_time; }PrivInfo; void info_init(PrivInfo *thiz); void *pthread_function1(void *paramthiz); void *pthread_function2(void *paramthiz); int main (int argc, char** argv) { pthread_t pt_1 = 0; pthread_t pt_2 = 0; int ret = 0; PrivInfo *thiz = NULL; thiz = (PrivInfo*)malloc(sizeof(PrivInfo)); if(NULL == thiz) { return -1; } info_init(thiz); ret = pthread_create(&pt_1, NULL, pthread_function1, (void*)thiz); if(0 != ret) { perror("pthread1 creation failed!"); } ret = pthread_create(&pt_2, NULL, pthread_function2, (void*)thiz); if(0 != ret) { perror("pthread2 creation failed!"); } pthread_join(pt_2, NULL); pthread_mutex_destroy(&thiz->mutex); free(thiz); thiz = NULL; return 0; } void info_init(PrivInfo *thiz) { return_if_fail(&thiz != NULL); thiz->lock_var = 0; thiz->end_time = time(NULL) 10; pthread_mutex_init(&thiz->mutex, NULL); return; } void *pthread_function1(void *paramthiz) { int ret = 0; int i = 0; PrivInfo *thiz = (PrivInfo *)paramthiz; while(time(NULL) < thiz->end_time) { ret = pthread_mutex_loc |
凌众科技专业提供服务器租用、服务器托管、企业邮局、虚拟主机等服务,公司网站:http://www.lingzhong.cn 为了给广大客户了解更多的技术信息,本技术文章收集来源于网络,凌众科技尊重文章作者的版权,如果有涉及你的版权有必要删除你的文章,请和我们联系。以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢! |
你可能对下面的文章感兴趣
上一篇: RH033学习资料下载下一篇: shell脚本中实现大段代码的注释方法
关于Linux下多线程编程简介(三)的所有评论