多线程实验
1.创建线程 定义线程函数 保护线程,退出时清除资源 定义清除函数
2.当主进程中用pthread_join时,先执行线程,主进程等待相应线程执行结束,再执行。
否则,先执行主进程,主进程中若sleep,则执行线程,否则主进程直接执行结束。
#include <pthread.h> #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <errno.h> int a = 1;
void *clean(void *arg) { printf("cleanup :%s\n", (char *)arg); //change the type of arg
return (void *)0; //the type of return is *p
} void *pth1 (void *arg) { pthread_cleanup_push((void *)clean, "thread 1"); //resource recovery
int *num; num = (int *)arg; //change the type of parametre
a++; printf("pthread:a = %d\n", a); printf("the num=%d\n", *num); pthread_exit((void *)1); pthread_cleanup_pop(0); //resource recovery when exit
return (void *)0; }
main(void) { int num = 4; pthread_t tidp; a++; int *arg = # //change the type of parametre
if(pthread_create(&tidp, NULL,(void *)pth1,(void *)arg) < 0) { printf("create error:%s\n", strerror(errno)); exit(1); } pthread_join(tidp,NULL); printf("main:a = %d\n", a); // sleep(1);
printf("this is process!\n"); }
|
易错点:
1.pthread_create 函数中参数的类型
2.void *pth1 (void *arg) 线程函数为返回值为指针的函数
阅读(1390) | 评论(0) | 转发(0) |