在Linux系统编程中,多线程是一种重要的并发编程技术,它允许一个进程内同时运行多个执行流,从而提高程序的效率和响应能力。而线程控制则是对这些线程进行管理的基础,包括线程的创建、等待和终止。本文将详细讲解这些核心操作,即使你是初学者也能轻松掌握。
创建线程是多线程编程的第一步,Linux提供了函数。函数原型如下:
#include
int pthread_create(pthread_t thread, const pthread_attr_t attr, void (start_routine) (void ), void arg);
- thread:指向pthread_t类型的指针,用于存储新线程的ID。
- attr:线程属性,通常设为NULL使用默认属性。
- start_routine:线程要执行的函数,格式为。
- arg:传递给线程函数的参数。
返回值:成功返回0,失败返回错误码。下面是一个简单的创建线程示例:
GPT plus 代充 只需 145#include#include void thread_func(void arg) { printf(“子线程开始运行,参数为:%s”, (char*)arg); return NULL;}int main() // 注意:这里需要等待线程结束,否则主线程可能先退出 pthread_join(tid, NULL); return 0;}
通过,我们可以轻松开启一个新的执行流。
当主线程(或其他线程)需要等待某个线程结束并获取其返回值时,可以使用函数。它类似于进程中的。函数原型:
int pthread_join(pthread_t thread, void retval);
- thread:要等待的线程ID。
- retval:指向指针的指针,用于存储线程的返回值(如果不关心可设为NULL)。
调用的线程会阻塞,直到目标线程终止。正确使用pthread_join可以避免僵尸线程,并获取线程的退出信息。示例:
GPT plus 代充 只需 145void calc(void arg) { int num = (int)arg; int *result = malloc(sizeof(int)); result = (num) * 2; return (void)result;}int main() { pthread_t tid; int input = 10; pthread_create(&tid, NULL, calc, &input); void ret; pthread_join(tid, &ret); printf(“线程计算结果:%d”, (int)ret); free(ret); return 0;}
线程可以在执行完毕后自然返回,也可以主动调用终止自己,或被其他线程通过取消。
在线程函数中调用可以立即终止当前线程,并返回给等待它的线程(如果有)。注意,如果主线程调用,进程不会终止,只会结束主线程,其他线程继续运行。示例:
void worker(void arg) { static int status = 100; printf(“工作线程正在执行…”); pthread_exit((void)&status);}int main() { pthread_t tid; void ret; pthread_create(&tid, NULL, worker, NULL); pthread_join(tid, &ret); printf(“线程退出状态:%d”, (int)ret); return 0;} 一个线程可以向另一个线程发送取消请求,使用。被取消的线程会在特定的取消点(如、、等系统调用)响应取消请求。如果线程需要被立即取消,可以设置取消类型为异步。示例:
GPT plus 代充 只需 145void busy(void* arg) { while(1) { printf(“工作中…”); sleep(1); } return NULL;}int main() { pthread_t tid; pthread_create(&tid, NULL, busy, NULL); sleep(3); pthread_cancel(tid); pthread_join(tid, NULL); printf(“线程已被取消”); return 0;}
本文详细介绍了Linux下多线程的线程控制三大基本操作:使用pthread_create创建线程,用pthread_join等待线程结束,以及通过和终止线程。掌握这些函数是编写健壮多线程程序的基础。在实际开发中,还需要注意线程同步(互斥锁、条件变量等),但本文聚焦于控制层面。希望这篇教程能帮助你开启Linux多线程编程的大门!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/240403.html