c语言线程终止练习示例

时间:2021-05-20

复制代码 代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

void *t1(void *args) {
return (void *) 0;
}

void *t2(void *args) {
printf("thread 2 param[args] = %d\n", args);
pthread_exit((void *) 3);
}

void *t3(void *args) {
while(1) {
printf("thread 3 is working\n");
sleep(1);
}
}

int main(int argc, char *argv[]) {
pthread_t thread;
int err;
void *status;

printf("creating thread 1\n");
err = pthread_create(&thread, NULL, t1, NULL);
if(err) {
printf("Can not created thread 1\n");
exit(-1);
}
pthread_join(thread, &status);
printf("thread 1 exit return code %d\n\n", status);

printf("creating thread 2\n");
err = pthread_create(&thread, NULL, t2, (void *) 9);
if(err) {
printf("Can not created thread 2\n");
exit(-2);
}
pthread_join(thread, &status);
printf("thread 2 exit return code %d\n\n", status);


printf("creating thread 3\n");
err = pthread_create(&thread, NULL, t3, NULL);
if(err) {
printf("Can not created thread 3\n");
exit(-3);
}
sleep(10);
pthread_cancel(thread);
pthread_join(thread, &status);
printf("thread 3 exit return code %d\n", status);

return 1;
}

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章