Linux多线程函数pthread_create()函数
2013-08-08 21:13
330 查看
函数原型:
#include <pthread.h>
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);
4个参数:
第一个参数:指向线程标示符pthread_t的指针;
第二个参数:设置线程的属性
第三个参数:线程运行函数的起始地址
第四个参数:运行函数的参数
pthreadTest.c
通过pthread_self()获取当前线程的ID
运行结果:
pthreadTest1.c
gcc -o pthreadTest1 pthreadTest1.c -lpthread
./pthreadTest1
main thread pid 10437 tid 3091662592 (0xb8470700)
new thread: pid 10437 tid 3083364096 (0xb7c86700)
#include <pthread.h>
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);
4个参数:
第一个参数:指向线程标示符pthread_t的指针;
第二个参数:设置线程的属性
第三个参数:线程运行函数的起始地址
第四个参数:运行函数的参数
pthreadTest.c
通过pthread_self()获取当前线程的ID
#include<stdio.h> #include<pthread.h> void *print_pthread_id(void *arg) { printf("current thread id is %u\n",(unsigned)pthread_self()); } int main(int argc, char * argv[]) { pthread_t thread; pthread_create(&thread,NULL,print_pthread_id,NULL); sleep(1); printf("main thread id is %u\n",(unsigned)pthread_self()); return 0; }编译时必须加-lpthread,
运行结果:
current thread id is 2279393024 main thread id is 2287691520
pthreadTest1.c
#include<stdio.h> #include<pthread.h> #include<stdlib.h> #include<unistd.h> #include<string.h> pthread_t t_id; void printf_tid_pid(const char *s) { pid_t pid; pthread_t tid; pid = getpid(); tid = pthread_self(); printf("%s pid %u tid %u (0x%x)\n",s,(unsigned)pid,(unsigned)tid,(unsigned)tid); } void *thread_fuction(void *arg) { printf_tid_pid("new thread: "); return ((void*)0); } int main(int argc,int argv) { int err; err = pthread_create(&t_id,NULL,thread_fuction,NULL); if(err != 0 ) { printf("create thread fail: %s\n",strerror(err)); } printf_tid_pid("main thread"); sleep(1); return 0; }
gcc -o pthreadTest1 pthreadTest1.c -lpthread
./pthreadTest1
main thread pid 10437 tid 3091662592 (0xb8470700)
new thread: pid 10437 tid 3083364096 (0xb7c86700)
相关文章推荐
- 编写线程函数时,链接时报错:undefined refrence to 'pthread_create '
- C++中使用pthread.h头文件报错 - 无法解析的外部符号 __imp__pthread_create,该符号在函数 _main 中被引用
- 线程创建函数pthread_create的pthread_attr_t类型的参数
- linux编程之pthread_create函数
- pthread_create()和pthread_atfork()函数使用时应注意的问题
- c++里的 pthread_create 函数小结
- pthread_create()函数用法
- 线程的创建pthread_create()函数(线程一)
- pthread_create()函数样例
- 基于pthread_create,readlink,getpid等函数的学习与总结
- pthread_create()函数用法
- pthread_create函数编译时报错:undefined reference to 'pthread_create'
- pthread_create 函数
- 类成员函数作为pthread_create函数参数
- pthread_create()函数样例
- pthread库中操作线程专有数据的函数:pthread_key_create,pthread_setspecific,pthread_gtespecific,pthread_key_delete
- linux函数之pthread_create
- pthread_create()函数
- 解决使用pthread_create函数造成的内存泄露
- C++使用线程函数pthread_create时,调用的成员函数要定义为静态成员函数