队列2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include <Windows.h>
#include <iostream>
#include <queue>
#include <stdio.h>
using namespace std;
 
DWORD WINAPI Receive(LPVOID lpParameter);//thread data
DWORD WINAPI Write(LPVOID lpParameter);//thread data
 
CRITICAL_SECTION  g_cs;
 
std::queue<int> i_queue;//编号
std::queue<void *> p_queue;//数据
FILE * pf=NULL;
 
void WriteData(void * pData)//把数据写入到硬盘
{
    pf=fopen("d:\\result.txt","at");
    int mm=fwrite(pData,sizeof(char),strlen((char *)pData),pf);
    fflush(pf);
}
void main()
{
    HANDLE hThread1,hThread2;
    hThread1 = CreateThread(NULL,0,Receive,NULL,0,NULL);
    hThread2 = CreateThread(NULL,0,Write,NULL,0,NULL);
    /*CloseHandle( hThread1 );
    CloseHandle( hThread2 );*/
    //InitializeCriticalSection(&g_cs); //
     
    Sleep(2000);
    while (i_queue.size()>0)
    {
        Sleep(100);
    }
    Sleep(2000);
    fclose(pf);
 
    //DeleteCriticalSection(&g_cs);
}
 
 
int i=0;
//线程1的入口函数
DWORD WINAPI Receive(LPVOID lpParameter)
{
    while (i<10)//运行10次就结束
    {
        //EnterCriticalSection(&g_cs);//
 
        i_queue.push(i);
        void * data=fopen("d:\\test.txt","at");
        p_queue.push(data);
        std::cout <<"接收线程:入队的与元素为 "<<i<<endl;
        if (i_queue.empty())
        {
            std::cout << "接收线程:队列为空" << endl;
        }
        else
        {
            std::cout << "接收线程: 队列元素个数" << i_queue.size() << endl;
        }
        i++;
        //LeaveCriticalSection(&g_cs);
        Sleep(500);
    }
 
    return 0;
}
//线程2的入口函数
DWORD WINAPI Write(LPVOID lpParameter)//thread data
{
    while (true)
    {
        //EnterCriticalSection(&g_cs);
        if (i_queue.empty())
        {
            std::cout << "IO线程:队列为空" << endl;
        }
        else
        {
            int aa=i_queue.front();
            int count=i_queue.front();
             
            void * newData=p_queue.front();
            std::cout << "IO线程:出队的数据"<<count<< endl;
            std::cout << "IO线程: 队列元素个数" << i_queue.size() <<endl;
            WriteData(newData);
            p_queue.pop();
            i_queue.pop();
        }
        //LeaveCriticalSection(&g_cs);
        Sleep(1300);
    }
    return 0;
posted @ 2016-05-11 12:11  投机者  阅读(101)  评论(0编辑  收藏  举报