C语言线程基本函数

学习笔记:

  • C语言线程基本函数

学习内容:

线程常用基本函数:

  1. pthread_create() 创建线程
  2. pthread_exit() 退出当前线程
  3. pthread_join() 等待其他线程结束
  4. pthread_self() 自身线程ID号
  5. pthread_cancel() 停止其他线程
  6. pthread_detach() 分离某个线程

学习笔记:

线程使用需要导入对应头文件

  • #include <pthread.h>

pthread_create() 创建线程

函数原型:

/**
 * @brief 创建一个线程
 * @param th 线程ID
 * @param attr 线程属性,通常使用NULL
 * @param func 线程函数入口
 * @param arg 线程函数传参
 * @return int 创建成功返回0,失败返回错误代码
 */
int pthread_create(pthread_t *th, 
                   const pthread_attr_t *attr, 
                   void *(* func)(void *), 
                   void *arg);

pthread_exit() 退出当前线程

函数原型:

/**
 * @brief 终止当前线程
 * @param res 向其他线程传送数据,(不能用局部变量传出)
 */
void pthread_exit(void *res);
  • res 用法见示例代码

pthread_join() 等待其他线程结束

函数原型:

/**
 * @brief 等待 th 线程结束
 * @param th 线程ID
 * @param res 用于线程退出时向外传送数据,
 *            当没有需要传出的数据时为NULL
 * @return int 成功0;失败返回错误码
 */
int pthread_join(pthread_t th, void **res);

pthread_self() 自身线程ID号

函数原型:

/**
 * @brief 返回自身的线程ID
 * @return pthread_t 
 */
pthread_t pthread_self(void);

pthread_cancel() 停止其他线程

函数原型:

/**
 * @brief 在其他线程中强行取消一个执行中的线程
 * @param th 目标线程ID
 * @return int 成功地发送了 Cancel 信号,返回数字 0;
 * 			   反之如果发送失败,函数返回值为非零数
 */
int pthread_cancel(pthread_t th);

pthread_detach() 分离某个线程

函数原型:

/**
 * @brief 分离某个线程
 * @note 如果对某个线程使用了pthread_detach,
 *       那么在其他线程中无法使用   pthread_join
 * @param th 
 * @return int 成功:0;失败:错误号
 */
int pthread_detach(pthread_t th);
  • 如果对某个线程使用了pthread_detach,那么在其他线程中无法使用 pthread_join

示例程序:

demo:

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

#define OPEN_DEBUG_MESSAGE   
#ifdef OPEN_DEBUG_MESSAGE
#   define D_MES(message) printf(message)
#else
#   define D_MES(message)        
#endif


typedef struct TResultTag TRes;
struct TResultTag
{
    char data[20];
    int num;
};

void *task1_entry(void *param)
{
    TRes *res = (TRes *)param;
     
    int i;
    for(i = 0; i < 10; i++)
    {
        printf("task i -> %d\n",i);
        sleep(1);
    }
    sprintf(res->data, "task1 id:%lu", pthread_self()); 
    res->num = 520;

    pthread_exit(param);
}

int main()
{
    printf("hello\n");
    
    // 用于子线程结束后传出返回值
    TRes *res = (TRes *)malloc(sizeof(TRes));
    if (res != NULL)
    {   
        pthread_t task1;
        
        // 创建线程
        if (pthread_create(&task1, NULL, task1_entry, res) != 0)
        	printf("failed in pthread_create \n");
        
        sleep(1);
        // pthread_detach(task1);  // 打开该行 pthread_join 会失败 
	
        int i;
        for(i = 0; i < 5; i++)
        {
        	printf("main i -> %d\n",i);
        	sleep(1);
        }
        
        // 等待线程 task1 结束
        if (pthread_join(task1, (void **)&res) == 0)
        // 输出由 task1 传出的返回值
            printf("res->data:%s\nres->:%d\n", res->data, res->num);
        else
            printf("ERROR: pthread_join");

    }
    else    
        printf("failed in malloc\n");

    system("pause");
    
    return 0;    
} 

效果截图

  • 不执行pthread_detach()
    在这里插入图片描述

  • 执行pthread_detach()
    在这里插入图片描述

  • 5
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
C语言中,创建线程需要使用线程函数库(pthread)。通过调用pthread_create函数来创建一个子线程,需要指定一个处理函数,该函数会在子线程中执行。创建线程的示例代码如下: ```c #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <pthread.h> // 子线程的处理函数 void* working(void* arg) { printf("我是子线程,线程ID:%ld\n", pthread_self()); for(int i=0; i<9; i++) { printf("child==i:=%d\n", i); } return NULL; } int main() { // 创建一个子线程 pthread_t tid; pthread_create(&tid, NULL, working, NULL); printf("子线程创建成功,线程ID:%ld\n", tid); // 子线程不会执行下边的代码,主线程执行 printf("我是主线程,线程ID:%ld\n", pthread_self()); for(int i=0; i<3; i++) { printf("i=%d\n", i); } return 0; } ``` 在上述代码中,我们通过调用`pthread_create`函数来创建了一个子线程,并在子线程中执行了`working`函数。主线程和子线程是同时执行的,它们的执行顺序可能是不确定的。需要注意的是,主线程会在子线程之前执行完毕。 除了创建线程线程函数库还提供了其他一些常用的函数,比如线程分离和线程取消等功能。如果需要将子线程和主线程分离,可以使用`pthread_detach`函数。示例代码如下: ```c #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <pthread.h> // 子线程的处理函数 void* working(void* arg) { printf("我是子线程,线程ID:%ld\n", pthread_self()); for(int i=0; i<9; i++) { printf("child==i:=%d\n", i); } return NULL; } int main() { // 创建一个子线程 pthread_t tid; pthread_create(&tid, NULL, working, NULL); printf("子线程创建成功,线程ID:%ld\n", tid); // 主线程执行 printf("我是主线程,线程ID:%ld\n", pthread_self()); for(int i=0; i<3; i++) { printf("i=%d\n", i); } // 设置子线程和主线程分离 pthread_detach(tid); // 让主线程自己退出即可 pthread_exit(NULL); return 0; } ``` 在上述代码中,我们通过调用`pthread_detach`函数将子线程和主线程分离。这样主线程执行完毕后会自动退出,不会等待子线程的结束。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [C语言线程库的使用,这篇值得收藏!](https://blog.csdn.net/LxXlc468hW35lZn5/article/details/125650245)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值