c语言线程 c语言线程终止练习示例

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

c语言线程 c语言线程终止练习示例

  2021-03-19 我要评论
想了解c语言线程终止练习示例的相关内容吗,在本文为您仔细讲解c语言线程的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:c语言线程,下面大家一起来学习吧。

复制代码 代码如下:

#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;
}

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们