C 创建线程的简单例子

本文通过一个C语言编写的多线程程序实例,演示了如何在Linux环境下使用pthread库创建和管理两个并发线程。线程A和线程B交替打印字符串,展示了线程间的调度和资源竞争现象。

1,thread_test.c

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

// 线程A
void* print_a(void *a)
{
    int i;
    for(i=0; i < 10; i++)
    {
        sleep(1);
        puts("aa");
    }
    return NULL;
}

// 线程B
void* print_b(void* b)
{
    int i;
    for(i=0; i<20; i++)
    {
        sleep(1);
        puts("bb");
    }
}

int main()
{
    pthread_t t0;
    pthread_t t1;

    // 创建线程A
    if(pthread_create(&t0, NULL, print_a, NULL) == -1)
    {
        puts("fail to create pthread t0");
        exit(1);
    }

    // 创建线程B
    if(pthread_create(&t1, NULL, print_b, NULL) == -1)
    {
        puts("fail to create pthread t1");
        exit(1);
    }

    // 等待线程结束
    void* result;
    if(pthread_join(t0, &result) == -1)
    {
        puts("fail to recollect t0");
        exit(1);
    }

    if(pthread_join(t1, &result) == -1)
    {
        puts("fail to recollect t1");
        exit(1);
    }

    return 0;
}

2,编译

gcc -lpthread -o thread_test thread_test.c

3,执行

./thread_test 
bb
aa
bb
aa
bb
aa
bb
aa
bb
aa
bb
...
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值