由printf()引出的c/c++运行时库问题
来源:互联网 发布:ubuntu如何读取u盘 编辑:程序博客网 时间:2024/06/05 10:51
在写多线程时写到这么一段代码:
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
DWORD WINAPI ThreadFunc(LPVOID);
void AnotherFunc(void);
int main()
...{
HANDLE hThrd;
DWORD exitCode=0;
DWORD threadId=0;
hThrd=CreateThread(NULL,0,ThreadFunc,(LPVOID)1,0,&threadId);
if(hThrd)
...{
printf("launched ");
}
for(;;)
...{
BOOL rc;
rc=::GetExitCodeThread(hThrd,&exitCode);
if(rc && exitCode!=STILL_ACTIVE)
break;
}
::CloseHandle(hThrd);
printf("returned %d ",exitCode);
return EXIT_SUCCESS;
}
DWORD WINAPI ThreadFunc(LPVOID n)
...{
//Sleep( 100 );
printf("running ");
AnotherFunc();
return 0;
}
void AnotherFunc()
...{
::ExitThread(4);
}
打印出来的结果是:
launched
launched
running
returned 4
奇怪!怎么printf()执行了2次呢?去网上查了一下,原来我调用的printf是非线程安全版本的C运行时库 这个版本的printf内部使用了全局的缓冲区,当另外一个线程调用printf时,将launched重复打印了,我可以这样进行设置:
改用Multithreaded多线程版本的C运行时库
在Project->Settings->C/C++->Code Generation->Multithreaded
还有几个都可以选
Multithreaded DLL
Debug Multithreaded
Debug Multithreaded DLL
附:在网上搜到一篇不错的介绍这方面的文章:
1)运行时库就是 C run-time library,是 C 而非 C++
4)C run-time library里面含有初始化代码,还有错误处理代码(例如divide by zero处理)。你写的程序可以没有math库,程序照样运行,只是不能处理复杂的数学运算,不过如果没有了C run-time库,main()就不会被调用,exit()也不能被响应。因为C run-time library包含了C程序运行的最基本和最常用的函数。
6)Windows环境下,VC提供的 C run-time library又分为动态运行时库和静态运行时库。
动态运行时库主要是DLL库文件msvcrt.dll(or MSVCRTD.DLL for debug build),对应的Import library文件是MSVCRT.LIB(MSVCRTD.LIB for debug build)
静态运行时库(release版)对应的主要文件是:
LIBC.LIB (Single thread static library, retail version)
LIBCMT.LIB (Multithread static library, retail version)
编译时到底哪个C run-time library联入你的程序取决于编译选项:
/MD, /ML, /MT, /LD (Use Run-Time Library)
To find these options in the development environment, click Settings on the Project menu. Then click the C/C++ tab, and click Code Generation in the Category box. See the Use Run-Time Library drop-down box.
从程序可移植性考虑,如果两函数都可完成一种功能,选运行时库函数好,因为各个 C 编译器的生产商对标准C Run-time library提供了统一的支持.
- 由printf()引出的c/c++运行时库问题
- 由一道程序员面试宝典引出的问题-printf如何读入浮点数!
- C语言之编译器引出的问题
- 由实例计数器引出(C#)
- 由Struct 嵌套定义引出的问题
- 由OpenSessionInView引出的List复制问题
- 由HTTP500错误引出的问题案例
- 由火车进站引出的问题
- Linux下的C语言pow()函数引出的问题
- 由一个语句引出的关于C的变量和常量的相关知识
- 水滴石穿C语言之编译器引出的问题
- 水滴石穿C语言之编译器引出的问题
- 水滴石穿C语言之编译器引出的问题
- 【转】水滴石穿C语言之编译器引出的问题
- 一个C笔试题引出一系列的问题
- 一个C笔试题引出一系列的问题
- 由NSString的copy和strong/retain引出o-c的copy机制 (一)
- 由NSString的copy和strong/retain引出o-c的copy机制 (二)
- 同一个service调用多个dao的事务问题
- ubuntu下sudo和root帐户关系的小总结
- 如何选用开源代码
- ubuntu命令大全
- 使用svn命令行递归的添加文件
- 由printf()引出的c/c++运行时库问题
- 重构 — 改善既有的类图设计 条款3:用 FACADE 类消除依赖关系的交叉
- 实现页面局部内容滚动
- Visual Leak Detector检测内存泄漏工具
- 魔方视频教程下载
- 误传了数千年的几个名句
- Google Chart API 自动生成图表
- 用YSlow来进行网页性能评估
- 使用CPU时间戳进行高精度计时