Linux:C-线程创建

线程创建

1,代码

项目名:pthread_create.c

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

/*
  getpid                获取进程ID
  pthread_self          获取线程ID

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

 第一个参数: 新线程ID, 创建成功系统回填
 第二个参数: 新线程到属性, NULL为默认属性
 第三个参数: 新线程到启动函数
 第四个参数: 传递给新线程
 
 */


void print_id(char *s){

        pid_t pid;
        pthread_t tid;

        pid = getpid();
        tid = pthread_self();

        printf("%s pid is %lu,   tid is %lx\n", s, pid,tid);

}

void *thread_func(void *arg){

        print_id(arg);

        return NULL;

}


int main(){


        pthread_t ntid;
        int err;

        err = pthread_create(&ntid, NULL,(void *)thread_func, "new thread");


        if(err!=0){ //创建成功返回0

                printf("create new thread is failed\n");
                return 0;
        }

        print_id("main thread: ");

        sleep(2);

        return 0;
}

2, 编译

gcc pthread_create.c -lpthread -o pthread_create

# 因为pthread库不是Linux系统默认的库, 所以编译时要连接连接库, 即加上 -lpthread

3, 执行

./pthread_create

4,结果

main thread:  pid is 58861,   tid is 7ff2d9767740
new thread pid is 58861,   tid is 7ff2d8f46700

5,总结

懵~~~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值