• 关于 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 下 运行的结果为

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

  • 相关阅读:
    Membership角色与权限管理
    Virtual PC 2007 下载地址
    Support Web Application Projects
    CSS使用高级技巧20则
    apache和IIS共用80端口
    Dreamweaver扩展(插件)使用
    CSS横向菜单下拉显示子菜单
    openPNE创建项目
    基础AJAX
    连接数据库
  • 原文地址:https://www.cnblogs.com/guoyu1024/p/9636218.html
Copyright © 2020-2023  润新知