linux:线程的控制
    		       		warning:
    		            这篇文章距离上次修改已过444天,其中的内容可能已经有所变动。
    		        
        		                
                在Linux中,你可以使用pthread库中的函数来控制线程。以下是一些常用的线程控制函数:
- pthread_create- 创建一个新的线程。
- pthread_exit- 终止当前线程。
- pthread_join- 等待另一个线程终止。
- pthread_cancel- 请求取消另一个线程。
- pthread_attr_init- 初始化线程属性。
下面是一个简单的例子,展示如何创建和终止一个线程:
#include <pthread.h>
#include <stdio.h>
 
void* thread_function(void* arg) {
    printf("线程运行中...\n");
    return NULL;
}
 
int main() {
    pthread_t thread;
    int ret;
 
    // 创建线程
    ret = pthread_create(&thread, NULL, thread_function, NULL);
    if (ret != 0) {
        printf("创建线程失败!\n");
        return -1;
    }
 
    // 等待线程结束
    pthread_join(thread, NULL);
 
    printf("线程已经结束!\n");
    return 0;
}在这个例子中,我们首先调用pthread_create来创建一个新的线程,然后调用pthread_join来等待新创建的线程执行结束。thread_function是新线程将要执行的函数。
请注意,编译时需要链接pthread库,使用gcc可以通过添加-lpthread参数来实现:
gcc -o thread_control thread_control.c -lpthread
评论已关闭