zoukankan      html  css  js  c++  java
  • gcc/clang编译带pthread.h头文件的源码时需要的参数

    今天敲了一个小程序,编译时出现错误:undefined reference pthread_create 

    原来由于pthread库不是Linux系统默认的库,连接时需要使用库libpthread.a,所以在使用pthread_create创建线程时,在编译中要加-lpthread参数:
    gcc -o test -lpthread test.c

    再查发现编译时参数写成 -pthread 也是可以的。

     * 经反复调试,此代码在多核环境下不安全,可能出现多个线程同时访问共享变量,
     * 即线程a将count读入操作,还未写回时刻,线程b也对count进行操作,则先完成
     * 操作的线程操作无效。
     * 后来发现,原来此不安全是因为,我写的函数是不可重入函数。 *

    #include <stdio.h> #include <pthread.h> #include <stdlib.h> #define NUMBER_OF_THREADS 10 int static count = 0; void *print_hello_world(void *tid) { pthread_yield(NULL); printf ("Hello world. Greetings from thread %lu %d ",pthread_self(),(int)tid); //long可以转换成int类型 count++; pthread_exit(NULL); } int main(int argc, char **argv) { pthread_t threads[NUMBER_OF_THREADS]; int status, i; for(i = 0; i < NUMBER_OF_THREADS; i++) { printf ("Main here. Creating thread %d ",i); status = pthread_create(&threads[i], NULL, print_hello_world,(void*)(long)i); //64位机子 int转指针类型会告警,故先转为long(64位)与指针位数相等 if(status != 0) { printf ("Oops. pthread_create returned error code %d ",status); exit(-1); } } for(i = 0; i < NUMBER_OF_THREADS; i++) { pthread_join(threads[i], NULL); printf ("Thread %d ended! ",i); } printf ("count=%d ",count); return 0; }

    xcode 中出现 Implicit declaration of function 'xxxx' is invalid in C99” 警告的解决办法

    该警告明确告诉我们在C99的规范中,不允许出现隐含声明的用法。这是C99规范中增加的规则,不过即便不遵守此规则,也仅仅是一个警告而已。


    什么是隐含声明呢,也很简单,就是你调用函数的c文件中,没有正确包含对应的头文件。一般来说,c,c++都会将类,函数,的声明放在头文件中,这样在需要的时候包含对应头文件就可以了,在编译器的前期处理中,需要通过头文件来建立一些函数,变量,类的表,如果调用到了声明中没有的函数,编译器会认为是有危险的,显而易见,如果直接调用函数,在运行期间会出现程序异常。


    因此强烈建议大家不要忽略这个警告,更不要象个别文章建议的那样把编译环境配置成C89,这样隐患依然存在。


    看来在解决这些警告之前,还是多了解一下C89, C99这些语言标准比较好。

  • 相关阅读:
    poj 1753 Flip Game
    SDIBT 2345 (3.2.1 Factorials 阶乘)
    HDU 1176 免费馅饼
    HDU 1058 Humble Numbers
    HDU 1003 MAXSUM(最大子序列和)
    HDU1864 最大报销额
    HDU 1114 Piggy-Bank(完全背包)
    POJ 3624 Charm Bracelet
    处理textarea里Enter(回车换行符)
    uniApp打卡日历
  • 原文地址:https://www.cnblogs.com/BinBinStory/p/7781823.html
Copyright © 2011-2022 走看看