#include <stdio.h> #include <pthread.h> #include <unistd.h> void *task (void * arg) { int i =0; while (1) { printf("i= %d\n",i++); sleep(2); } } void *task1 (void * arg) { int j =0; while (1) { printf("j= %d\n",j++); sleep(2); } } void *task2 (void * arg) { int k =0; while (1) { printf("k= %d\n",k++); sleep(2); } } int main(int argc, char const *argv[]) { pthread_t tid; pthread_create(&tid, NULL, task, NULL); pthread_t tid1; pthread_create(&tid1, NULL, task1, NULL); pthread_t tid2; pthread_create(&tid2, NULL, task2, NULL); //发送线程取消请求 int ch = 0; while (1) { printf("请输入停止的线程 1 2 3 \n"); scanf("%d\n",&ch); if(ch == 1) { pthread_cancel(tid); } if(ch == 2) { pthread_cancel(tid1); } if(ch == 3) { pthread_cancel(tid2); } } printf("线程已取消\n"); pause(); return 0; }
linux 多线程的创建和取消
于 2022-08-02 16:47:26 首次发布
关键词由CSDN通过智能技术生成