使用pthreads基本函数编写helloworld.c
来源:互联网 发布:单片机学习 编辑:程序博客网 时间:2024/06/09 17:05
Linux下的多线程程序使用pthread库。
对应函数有:
创建线程:pthread_create(pthread_t*, thrad, pthread_attr_t * attr, void* (start_routine)(void*)), void* arg);
退出线程:主动退出:pthread_exit(void* val); 被动退出:pthread_cancel(pthread_t thread);
等待线程结束替其清理内存:pthread_join(pthread_t thread, void** thread_return);
让线程退出时自己清理其内存:int pthread_detach(pthread_t th);
获得当前线程的标志:pthread_t pthread_self(void);
编译命令:gcc helloworld.c -o helloworld -lpthread -std=c99
/*************************************************************************> File Name: helloworld.c> Author: > Mail: > Created Time: Tue 23 Aug 2016 09:45:08 PM CST ************************************************************************/#include <stdio.h>#include <stdlib.h>#include <pthread.h>#include <unistd.h>#define THREAD_NUMBER 2int retval_hello1 = 1;int retval_hello2 = 2;void* hello1(void* arg){ char* hello_str = (char *)arg; sleep(1); printf("%s\n", hello_str); pthread_exit(&retval_hello1);}void* hello2(void* arg){ char* hello_str = (char *)arg; sleep(2); printf("%s\n", hello_str); pthread_exit(&retval_hello2);}int main(){ int retval; int *retval_hello[2]; pthread_t pt[2]; const char* arg[THREAD_NUMBER]; arg[0] = "hello world from thread1."; arg[1] = "hello world from thread2."; printf("begin to create threads....\n"); retval = pthread_create(&pt[0], NULL, hello1, (void*)arg[0]); if(retval != 0){ printf("pthread_create error."); exit(1); } retval = pthread_create(&pt[1], NULL, hello2, (void*)arg[1]); if(retval != 0){ printf("pthread_create error."); exit(1); } printf("now, the main thread returns.\n"); printf("main thread begin to wait threads.\n"); for(int i=0;i<THREAD_NUMBER;i++){ retval = pthread_join(pt[i], (void **)&retval_hello[i]); if(retval != 0){ printf("pthread_join error"); exit(1); }else{ // if(retval_hello[0] == &retval_hello1){ // printf("the same"); // } printf("return value is %d\n", *retval_hello[i]); } } return 0;}
运行结果
0 0
- 使用pthreads基本函数编写helloworld.c
- C函数基本使用
- ubuntu 下使用CGI c语言 编写helloworld
- 使用Geany编写一个 HelloWorld 的C语言程序+100以内素数+java helloworld
- pthreads 的基本用法
- pthreads 的基本用法
- pthreads 的基本用法
- 用Pthreads进行共享内存编程----HelloWorld
- pthreads几种锁使用
- apache module helloworld, Linux平台使用C编写网页 CGI helloword 实例
- 使用hibernate5.2.10编写hibernate helloworld
- 编程c++dll , DLL 的编写,导出函数 ,使用函数
- Pthreads
- pthreads
- pthreads
- windows 使用pthreads线程库
- Flask-HelloWorld-01 安装和基本使用
- Gradle 的基本使用 HelloWorld篇
- fastjson
- word选中段尾不选回车符
- Gulp+webpack模板化开发演练(1):分离公共头文件
- java.lang.SecurityException: Permission Denial:错误解决办法
- UVA 1331 Minimax Triangulation [最优三角剖分] [dp] [计算几何]
- 使用pthreads基本函数编写helloworld.c
- java--css(2)选择器
- 递归算法的一些实例
- @Autowired学习笔记
- Maven安装
- 如何指定tomcat下的某个项目的具体文件为网站的首页面
- 介绍 Android DropBoxManager Service
- Object-Oriented Analysis and Design Using UML 翻译与学习 (三)
- C++的inline