关于 Linux 下的线程函数未定义问题

#include<pthread.h>
#include<stdio.h>
#include<stdlib.h>
static int counter=0;
#define loops 10000000
static void* thread(void *unused)
{
    int i;
    for(i=0;i<loops;++i)
    {
        ++counter;
    }
    return NULL;
}
int main()
{
    pthread_t t1,t2;
    pthread_create(&t1,NULL,thread,NULL);
    pthread_create(&t2,NULL,thread,NULL);
    pthread_join(t1,NULL);
    pthread_join(t2,NULL);
    printf("counter is %d by thread\n",counter);
    return 0;
}

源文件名为 t.c  编译命令 为 gcc -o t -g t.c

无法编译 并提示

原因是 因为pthread库不是Linux系统默认的库

In general, libraries should follow sources and objects on command line, and -lpthread is not an "option", it's a library specification. 
On a system with only libpthread.a installed,

  

所以正确的命令如下    

 gcc -pthread -o t t.c

  产生输出

counter is 20000000 by thread

  以上代码实现了对同一个全局变量的自加运算 循环次数为一千万次。但该例子是一个线程不安全的代码

而在 windows 下 运行的结果为

之所以选择一千万 是为了保证第一个线程不要再第二个线程开始前就结束运行。

 

转载于:https://www.cnblogs.com/guoyu1024/p/9636218.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值