C语言:记录在主线程中停止子线程

主线程中创建一个子线程如代码:

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <signal.h>

void sighandler(int signum)
{
    printf("Pthread stop singal.\n");
    pthread_exit(0);
}
void *test(void *arg)
{
	signal(SIGALRM, sighandler);
    while(1){
        printf("111\n");
        sleep(1);
    }
}
int main()
{
    pthread_t pth;
    pthread_create(&pth, NULL, test, NULL);
    pthread_detach(pth);

    sleep(5);
    int rc = pthread_kill(pth, SIGALRM);
    printf("rc = %d\n",rc);
    while(1);
}

想要杀死子线程,首先需要子线程detach主线程,这样子线程不被主线程控制,然后主线程启用kill信号,子线程接收到信号后做信号处理函数进行exit。

另一种方法是pthread_cancle(),具体使用方法进行了测试,在此不提供。

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C语言线程线程之间可以使用共享内存、信号量、消息队列等方式进行通信。下面是一个使用共享内存进行通信的示例代码: 线程: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> #include <unistd.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #define SHM_SIZE 1024 int main() { int shmid; key_t key; char *shm, *s; // 创建共享内存 key = ftok(".", 'a'); shmid = shmget(key, SHM_SIZE, IPC_CREAT | 0666); if (shmid == -1) { perror("shmget"); exit(1); } // 将共享内存附加到当前进程 shm = shmat(shmid, NULL, 0); if (shm == (char *) -1) { perror("shmat"); exit(1); } // 向共享内存写入数据 strcpy(shm, "Hello, world!"); // 创建线程 pthread_t tid; if (pthread_create(&tid, NULL, child_thread, (void *) &shmid) != 0) { perror("pthread_create"); exit(1); } // 等待线程结束 if (pthread_join(tid, NULL) != 0) { perror("pthread_join"); exit(1); } // 从共享内存读取数据 for (s = shm; *s != '\0'; s++) { putchar(*s); } putchar('\n'); // 分离共享内存 if (shmdt(shm) == -1) { perror("shmdt"); exit(1); } // 删除共享内存 if (shmctl(shmid, IPC_RMID, NULL) == -1) { perror("shmctl"); exit(1); } return 0; } ``` 线程: ```c void *child_thread(void *arg) { int shmid = *(int *) arg; char *shm, *s; // 将共享内存附加到当前进程 shm = shmat(shmid, NULL, 0); if (shm == (char *) -1) { perror("shmat"); exit(1); } // 在共享内存追加数据 for (s = shm; *s != '\0'; s++) { *s = toupper(*s); } // 分离共享内存 if (shmdt(shm) == -1) { perror("shmdt"); exit(1); } pthread_exit(NULL); } ``` 在这个示例线程线程都可以访问同一个共享内存区域,线程向共享内存写入数据,线程将数据转换为大写字母后再追加到共享内存。最终,线程从共享内存读取数据并输出。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值