C语言的多线程

目录

一、 多线程创建

1). 头文件

2). 函数 API 接口


一、 多线程创建

1). 头文件

#include <pthread.h> 

2). 函数 API 接口

1. 线程的标识

函数原型

pthread_t pthread_self(void);

返回值

返回线程号

例子

#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
​
int main()
{
    pid_t pid;
    pthread_t thread_id;
 
    pid = getpid();
    thread_id = pthread_self();
 
    printf("pid = %d\nthread_id = %lu\n", (int)pid, (unsigned long)thread_id);
    return 0;
}

2. 线程的创建

函数原型

int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void* (*start_routine)(void*), void*arg)

返回值

成功:0;失败:错误码

参数列表

pthread_t*thread:线程id
​
constpthread_attr_t *attr:线程属性,NULL(由系统分配属性)
​
void* (*start_routine) (void*):线程执行函数
​
void* arg:线程创建时传递的参数,不传递时写NULL

例子

#include<pthread.h>
#include<stdio.h>
 
void *producer(void *arg)
{
    int p = 0;
    printf("进入当前线程 producer\n");
    sleep(2);
}
​
int main(int argc, char *argv[])
{
    int err;
    pthread_t cid;
    
    pthread_create(&cid, NULL, producer, NULL);
    if(err!=0){
        printf("thread error\n");
        return-1;
    }
    
    pthread_join(cid, NULL);
    printf("线程结束\n");
    return 0;
}

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值