首页 > 代码库 > 线程的创建,pthread_create,pthread_self,pthread_once
线程的创建,pthread_create,pthread_self,pthread_once
typedef unsigned long int pthread_t;
//come from /usr/include/bits/pthreadtypes.h
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);创建新的线程
pthread_t pthread_self(void);获取本线程的线程ID
int pthread_equal(pthread_t t1, pthread_t t2);判断两个线程ID是否指向同一线程
int pthread_once(pthread_once_t *once_control, void (*init_routine) (void));用来保证init_routine线程函数在进程中只执行一次。
#include <stdio.h> #include <pthread.h> #include <unistd.h> #include <stdlib.h> int* thread_func(void* arg) { pthread_t new_thid; new_thid = pthread_self();//打印线程自己的线程ID printf("the new thread, ID is %lu\n", new_thid); return NULL; } int main() { pthread_t thid; printf("main thread, ID is %lu\n", pthread_self());//打印主线程自己的线程ID if (pthread_create(&thid, NULL, (void*)thread_func, NULL) != 0) { printf("create thread failed\n"); exit(0); } sleep(5); return 0; }
某些情况下,函数执行次数要被限制为1次,这种情况下,要使用pthread_once,代码示例:
#include <stdio.h> #include <pthread.h> #include <unistd.h> #include <stdlib.h> pthread_once_t once = PTHREAD_ONCE_INIT; void run(void) { printf("function run is running in thread:%lu\n", pthread_self()); } int* thread1(void* arg) { pthread_t new_thid; new_thid = pthread_self(); printf("current thread ID is %lu\n", new_thid); pthread_once(&once, run); printf("thread1 end\n"); return NULL; } int* thread2(void* arg) { pthread_t new_thid; new_thid = pthread_self(); printf("current thread ID is %lu\n", new_thid); pthread_once(&once, run); printf("thread2 end\n"); return NULL; } int main() { pthread_t thid1, thid2; printf("main thread, ID is %lu\n", pthread_self()); pthread_create(&thid1, NULL, (void*)thread1, NULL); pthread_create(&thid2, NULL, (void*)thread2, NULL); sleep(5); printf("main thread exit\n"); return 0; }
运行结果:
main thread, ID is 3076200128
current thread ID is 3067804480
function run is running in thread:3067804480
thread2 end
current thread ID is 3076197184
thread1 end
main thread exit
虽然在thread1 跟thread2中都调用了run函数,但是run函数只执行了一次。
线程的创建,pthread_create,pthread_self,pthread_once
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。