关于 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
",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