Linux多线程03-终止线程

pthread_exit 和 pthread_self 和 pthread_equal

描述:

pthread_exit

pthread_exit() 函数终止调用该函数的线程,并通过retval返回一个值,如果该线程是可连接的,则在同一进程中调用pthread_join(3)的另一个线程可以获取该值。

任何由pthread_cleanup_push(3)建立但尚未弹出的清理处理程序都会被弹出(按照它们被推入的相反顺序),并执行。如果线程有任何线程特定数据,则在执行清理处理程序后,将按照未指定的顺序调用相应的析构函数。

当线程终止时,进程共享资源(例如互斥量、条件变量、信号量和文件描述符)不会被释放,并且使用atexit(3)注册的函数不会被调用。

在进程中的最后一个线程终止后,进程通过使用退出状态为零调用exit(3)终止,因此释放进程共享资源并调用使用atexit(3)注册的函数。

pthread_self

pthread_self()函数返回调用线程的ID。这个值与在创建该线程的pthread_create(3)调用中*thread返回的值相同。

pthread_equal

pthread_equal()函数比较两个线程标识符。

#include <pthread.h>
void pthread_exit(void *retval);
    功能: 终止一个线程, 在哪个线程调用, 就表示终止哪个线程
    参数:
        retval: 需要传递一个指针, 可以传递NULL
                作为一个返回值, 可以在pthread_join()中获取到
    返回: 无

pthread_t pthread_self(void);
    功能: 获取当前线程的ID

int pthread_equal(pthread_t t1, pthread_t t2);
    功能:比较两个线程ID是否相等
        不同的操作系统, pthread_t类型实现不一样,有的长整形,有的结构体实现,
        所以需要交给API来判断
    返回:如果两个线程 ID 相等,则 pthread_equal() 返回非零值;
        否则,它将返回0.

Compile and link with -pthread.

代码实例

#include <stdio.h>
#include <pthread.h>
#include <string.h>

void* callback(void* arg) 
{
    //子线程和主线程是交替执行的
    *(pthread_t*)arg = pthread_self();
    printf("child thread id: %ld\n",*(pthread_t*)arg);
    return NULL; //pthread_exit(NULL)
}

int main(){
    pthread_t tid;
    pthread_t* childTid;
    int ret = pthread_create(&tid, NULL, callback, (void*)childTid);

    if(ret != 0)
    {
        char* errstr = strerror(ret);
        printf("error: %s\n", errstr);
    }

    //主线程
    int i = 0;
    for(;i<5;i++){
        printf("%d\n",i);
    }

    printf("tid: %ld, main thread id: %ld\n", tid, pthread_self());

    sleep(1);
    if(pthread_equal(tid, *childTid)){
        printf("是同一个子线程, ID相同\n");
    }

    //让主线程退出, 主线程退出时不会影响其他正常运行线程
    pthread_exit(NULL);
    
    return 0;
}

运行结果

0
1
2
3
4
tid: 140351754999552, main thread id: 140351763388224
child thread id: 140351754999552
是同一个子线程, ID相同
posted @ 2023-06-26 08:52  言叶以上  阅读(118)  评论(0编辑  收藏  举报