1.创建新的线程
#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<sys/types.h>
void *doit(void *arg){
printf("arg: %s\tpid: %d\ttid:%lu\n", (char *)arg, getpid(), pthread_self());
return NULL;
}
int main(void){
pthread_t tid;
//create a new thread;
pthread_create(&tid, NULL, doit, "New-thread");
//we have 2 threads now, main and new created thread;
//the 2 threads running asynchronous
sleep(1);
doit("main");
return 0;
}
编译运行:
zhongjun@Eclipse:~$ gcc pthread.c -lpthread
zhongjun@Eclipse:~$ ./a.out
arg: New-thread pid: 227 tid:140124534671104
arg: main pid: 227 tid:140124545353536
2.线程的分离
#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<sys/types.h>
void *doit(void *arg){
for(int i = 0; i < 5; i++){
printf("arg: %s\tpid: %d\ttid:%lu\n", (char *)arg, getpid(), pthread_self());
sleep(4);
}
return NULL;
}
int main(void){
pthread_t tid;
//create a new thread;
pthread_create(&tid, NULL, doit, "New-thread");
//detach new thread
pthread_detach(tid);
for(int i = 0; i < 5; i++){
printf("pid: %d\ttid: %lu\n", getpid(), pthread_self());
sleep(5);
}
return 0;
}
编译运行后,通过命令top -H -p "thread_id"
查看效果。
3.线程的汇合和终止
#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<sys/types.h>
void *handler(void *arg){
printf("I am running, handler...\n");
sleep(5);
return (void *)1;
}
void *handler_cancel(void *arg){
printf("Running thread cancel...\n");
while(1){
printf("cancel...\n");
sleep(2);
}
return NULL;
}
void *handler_exit(void *arg){
printf("handler-exit running...\n");
sleep(5);
pthread_exit((void *)5);
}
int main(void){
void *ret;
pthread_t tid;
pthread_create(&tid, NULL, handler, NULL);
//join thread, blocking mode
pthread_join(tid, &ret);
printf("exit now...%d\n", (int)ret);
//pthread_exit
pthread_create(&tid, NULL, handler_exit, NULL);
pthread_join(tid, &ret);
printf("Handler_exit code is: %d\n", (int)ret);
//thread cancel...
sleep(3);
pthread_create(&tid, NULL, handler_cancel, NULL);
pthread_cancel(tid);
pthread_join(tid, &ret);
if(ret == PTHREAD_CANCELED)
printf("handler func exit code is: %d\n", (int)ret);
return 0;
}
网友评论