如何在用C语言在windows下创建简单的多线程

以下代码实现了用C语言在控制台实现了创建两个线程,各自线程中对对应的全局变量进行叠加操作。

注意:

以下代码不能在gcc6.3.0中编译,否则会报错:more_thread.c:3:21: fatal error: pthread.h: No such file or directory。

在gcc13.2.0中可以正常编译执行。

#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
int count1 = 0;
int count2 = 0;
void *thread_func1(void* arg)
{
    while(1)
    {
        sleep(1);//sleep 1s
        count1++;
        printf("thread1 count1[%d]\r\n", count1);
    }
    return;
}
void *thread_func2(void* arg)
{
    while(1)
    {
        usleep(500000);//sleep 500ms
        count2++;
        printf("thread2 count2[%d]\r\n", count2);
        
    }
    return;
}

int main()
{
    pthread_t thread1;
    pthread_t thread2;
    //creat thread
    pthread_create(&thread1, NULL, thread_func1, NULL);
    pthread_create(&thread2, NULL, thread_func2, NULL);

    while(1)
    {
        printf("count1 [%d], count2 [%d]\r\n", count1, count2);
        sleep(1);
    }
    return 0;
}
 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值