Linux自主学习 - 多线程的创建(#include<pthread.h>)

该文展示了如何在Ubuntu中使用VSCode通过SSH连接到虚拟机,并进行C语言的多线程编程。代码示例使用了pthread_create函数创建两个线程,模拟龟兔赛跑场景,每个线程独立运行并睡眠不同时间。
摘要由CSDN通过智能技术生成

备注:vscode通过ssh连接虚拟机中的ubuntu,ubuntu-20.04.3-desktop-amd64.iso

函数pthread_create()

// pthread.h中的函数pthread_create()

extern int pthread_create
(
               pthread_t *__restrict __newthread,       // 线程标识符
			   const pthread_attr_t *__restrict __attr, // 线程属性
			   void *(*__start_routine) (void *), // 线程函数指针
			   void *__restrict __arg             // 线程函数指针的参数
)
__THROWNL __nonnull ((1, 3));

代码段

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

// 线程函数
void * th_fn(void * arg)
{
    int distance = (int)arg; // 龟兔赛跑的距离

    int i;
    // 对于turtle线程和rabbit线程来说,局部变量i不共享

    for(i=1; i<=distance; i++)
    {
        printf("线程%lx run %d\n", pthread_self(), i);
        int time = (int)(drand48() * 100000);
        usleep(time); // 睡眠time微秒
    }

    return (void *) 0;
}

int main(void)
{
    int err; // err用于接收pthread_create()的返回值
    pthread_t rabbit, turtle;

    // 创建turtle线程
    if((err = pthread_create(&turtle, NULL, th_fn, (void *)50)) != 0)
        perror("pthread_creat() error!");

    // 创建rabbit线程
    if((err = pthread_create(&rabbit, NULL, th_fn, (void *)50)) != 0)
        perror("pthread_creat() error!");

    // 主控线程
    pthread_join(rabbit, NULL); // 主控线程等待rabbit线程执行完成
    pthread_join(turtle, NULL); // 主控线程等待turtle线程执行完成
    printf("Main control thread id:%lx\n", pthread_self());
    printf("finished!\n");

    return 0;
}

对代码段进行编译:

gcc test_pthread_1.c -o test_pthread_1 -l pthread

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值