cout and printf 线程
来源:互联网 发布:幻灯片制作软件下载 编辑:程序博客网 时间:2024/06/05 17:45
因为这几天在学线程 所以用到cout输出 结果cout的输出 的数据是混乱的。
后来上网 找了下 网上说 cout没有线程安全,printf有线程安全。
然后我就把cout换成了 printf 进行输出数据,结果还是一样 还是会有个别的数据混乱。
后来又苦苦的上网找了半天才找到 了临界区。
CRITICAL_SECTION 用之前 要初始化InitializeCriticalSection ,
数据前 EnterCriticalSection 进入临界区,数据后 LeaveCriticalSection临界区 ,感觉就像 Com库中的 CoInitialize CoUninitialize 用单线程方式创建。
#include <string>#include <iostream>#include <windows.h>using namespace std;DWORD WINAPI MyThread(LPVOID lpParameter);DWORD WINAPI MyThread1(LPVOID lpParameter);int index=0;int tickets=10000; //票数CRITICAL_SECTION g_CS; //定义一个临界区int main(){//DWORD id;InitializeCriticalSection( &g_CS ); //对临界区初始化HANDLE hwnd=CreateThread(NULL,0,MyThread,NULL,0,NULL);HANDLE hwnd1=CreateThread(NULL,0,MyThread1,NULL,0,NULL);CloseHandle(hwnd);CloseHandle(hwnd1);Sleep(400000);return 0;}DWORD WINAPI MyThread(LPVOID lpParameter){while(true){if(tickets>0){//进化临界区EnterCriticalSection( &g_CS );//cout<<"thread 1 sell ticket:"<<tickets--<<endl;printf("thread 1 sell ticket :%d\n",tickets--);LeaveCriticalSection( &g_CS );//离开临界区}elsebreak;//Sleep(100);}return 0;}DWORD WINAPI MyThread1(LPVOID lpParameter){while(true){if(tickets>0){//进化临界区EnterCriticalSection( &g_CS );//cout<<"thread 2 sell ticket:"<<tickets--<<endl;printf("thread 2 sell ticket :%d\n",tickets--);LeaveCriticalSection( &g_CS );//离开临界区}elsebreak;//Sleep(100);}}return 0;}
0 0
- cout and printf 线程
- cout printf解释
- PRINTF 与 COUT 区别
- cout与printf
- std::cout和printf
- cout和printf
- cin cout scanf printf
- cout与printf
- cout与printf区别
- cout和printf机制
- Round #56,Clarke and puzzle,二维树状数组+博弈(printf速度快于cout)
- cout和printf的混用
- printf和cout的区别
- printf()和cout的区别
- cout和printf的区别
- float printf 和cout 疑问
- cout与printf分析比较
- printf和cout的速度
- 遇到一个经典问题:UBOOT中malloc函数返回值不对
- 黑马程序员_object c学习日记_复习Foundation
- UVa 11168 Airport 凸包
- RCC 2014 Warmup (Div. 2) A~C
- Python 序列的切片操作与技巧 详细讲解
- cout and printf 线程
- 《MQL4实用编程》读书笔记(8) - 简单编程:编写外建指标
- codeforces RCC2014 Warmup div2 A+B+C+D+E
- 把文件保存到 sdcard
- 阿里云:从防到攻,深入浅出DDoS
- Garbage collection in Java
- LeetCode(Minimum Path Sum) 找到路径中和最小的
- Java Collection Framework
- 不爱