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函数只执行了一次。
时间: 2024-10-19 19:44:36