栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Go语言

C语言线程基本函数

Go语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C语言线程基本函数

学习笔记:
  • C语言线程基本函数

学习内容:

线程常用基本函数:

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

学习笔记:

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

  • #include
pthread_create() 创建线程

函数原型:

int pthread_create(pthread_t *th, 
                   const pthread_attr_t *attr, 
                   void *(* func)(void *), 
                   void *arg);
pthread_exit() 退出当前线程

函数原型:

void pthread_exit(void *res);
  • res 用法见示例代码
pthread_join() 等待其他线程结束

函数原型:

int pthread_join(pthread_t th, void **res);
pthread_self() 自身线程ID号

函数原型:

pthread_t pthread_self(void);
pthread_cancel() 停止其他线程

函数原型:

int pthread_cancel(pthread_t th);
pthread_detach() 分离某个线程

函数原型:

int pthread_detach(pthread_t th);
  • 如果对某个线程使用了pthread_detach,那么在其他线程中无法使用 pthread_join
示例程序: demo:
#include 
#include 
#include 
#include 
#include 

#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 -> %dn",i);
        sleep(1);
    }
    sprintf(res->data, "task1 id:%lu", pthread_self()); 
    res->num = 520;

    pthread_exit(param);
}

int main()
{
    printf("hellon");
    
    // 用于子线程结束后传出返回值
    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 -> %dn",i);
        	sleep(1);
        }
        
        // 等待线程 task1 结束
        if (pthread_join(task1, (void **)&res) == 0)
        // 输出由 task1 传出的返回值
            printf("res->data:%snres->:%dn", res->data, res->num);
        else
            printf("ERROR: pthread_join");

    }
    else    
        printf("failed in mallocn");

    system("pause");
    
    return 0;    
} 

效果截图
  • 不执行pthread_detach()

  • 执行pthread_detach()

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/990145.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号