c语言线程怎么停止

停止C语言线程可以通过以下两种方式实现:,1、使用标志位控制线程的运行和停止:,在线程函数中定义一个标志位,用于表示线程是否继续运行。,在主线程或其他线程中修改标志位的值,以控制目标线程的运行和停止。,在目标线程的循环中不断检查标志位的值,如果为0,则退出循环,从而停止线程的执行。,2、使用信号量(Semaphore)控制线程的运行和停止:,在目标线程中使用sem_wait()函数等待信号量的值大于0,表示可以继续执行。,在主线程或其他线程中使用sem_post()函数释放信号量,使其值加1。,在目标线程中使用sem_wait()函数等待信号量的值大于0,表示可以继续执行。,在需要停止线程时,再次调用sem_post()函数释放信号量,由于信号量的值已经变为0,目标线程将不再等待信号量,从而停止执行。,下面是一个示例代码,演示了如何使用标志位来停止C语言线程:,在上面的示例代码中,我们定义了一个
stopFlag标志位和一个
threadFunc线程函数,在
main函数中创建了一个新线程,并将
stopFlag的地址作为参数传递给目标线程,然后主线程休眠5秒后,将
stopFlag设置为1,表示需要停止目标线程的执行,最后通过
pthread_join()函数等待目标线程结束执行。,
,#include <stdio.h> #include <pthread.h> #include <unistd.h> // 定义标志位 volatile int stopFlag = 0; void* threadFunc(void* arg) { int id = *((int*)arg); printf(“Thread %d started “, id); while (!stopFlag) { // 线程执行的任务代码 printf(“Thread %d is running “, id); sleep(1); // 模拟耗时操作 } printf(“Thread %d stopped “, id); return NULL; } int main() { pthread_t threadId; int id = 1; // 线程ID int status; // 创建线程并传入参数id和stopFlag的地址 status = pthread_create(&threadId, NULL, threadFunc, &id); if (status != 0) { printf(“Failed to create thread “); return 1; } // 主线程休眠5秒,给目标线程足够的时间执行一段时间 sleep(5); // 修改标志位为1,停止目标线程的执行 stopFlag = 1; printf(“Main thread stopped the target thread “); // 等待目标线程结束执行 status = pthread_join(threadId, NULL); if (status != 0) { printf(“Failed to join thread “); return 1; } return 0; },

版权声明:本文采用知识共享 署名4.0国际许可协议 [BY-NC-SA] 进行授权
文章名称:《c语言线程怎么停止》
文章链接:https://zhuji.vsping.com/469647.html
本站资源仅供个人学习交流,请于下载后24小时内删除,不允许用于商业用途,否则法律问题自行承担。