码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-09-12 20:16:42      阅读:238      评论:0      收藏:0      [点我收藏+]

标签:ops   千万   次数   分享   循环   选择   oop   代码   use   

#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 下 运行的结果为

技术分享图片

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

 

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

标签:ops   千万   次数   分享   循环   选择   oop   代码   use   

原文地址:https://www.cnblogs.com/guoyu1024/p/9636218.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!