CVI多线程数据保护(安全队列)

一个线程产生数据,加入安全队列;一个线程显示数据,读取安全队列。

#include 
#include   
#include 
int CVICALLBACK ThreadFunction (void *functionData);
int CVICALLBACK ThreadFunction1 (void *functionData);
int threadID;
int threadID1;

static int startflag = 0;
static int startflag1 = 0;
static CmtTSQHandle	g_timerQueueHdl = 0;

BOOL SetConsoleColor(WORD wAttributes)  
{  
    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);  
    if (hConsole == INVALID_HANDLE_VALUE)  
        return FALSE;     
    return SetConsoleTextAttribute(hConsole, wAttributes);  
} 
int main()  
{
	if (CmtNewTSQ (2, sizeof(long), OPT_TSQ_DYNAMIC_SIZE,&g_timerQueueHdl) < 0)
		return -1;
	startflag = 1;
	startflag1 = 1;
		SetConsoleColor(FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);    
	CmtScheduleThreadPoolFunction (DEFAULT_THREAD_POOL_HANDLE,ThreadFunction1 ,NULL ,&threadID1);

	CmtScheduleThreadPoolFunction (DEFAULT_THREAD_POOL_HANDLE,ThreadFunction ,NULL ,&threadID);	
	CmtWaitForThreadPoolFunctionCompletion (DEFAULT_THREAD_POOL_HANDLE,threadID, OPT_TP_PROCESS_EVENTS_WHILE_WAITING);  
	CmtReleaseThreadPoolFunctionID (DEFAULT_THREAD_POOL_HANDLE, threadID);
	CmtWaitForThreadPoolFunctionCompletion (DEFAULT_THREAD_POOL_HANDLE,threadID1, OPT_TP_PROCESS_EVENTS_WHILE_WAITING);  
	CmtReleaseThreadPoolFunctionID (DEFAULT_THREAD_POOL_HANDLE, threadID1);
	CmtDiscardTSQ (g_timerQueueHdl);
}
int CVICALLBACK ThreadFunction (void *functionData)
{
	long g_nNum[2] = {0,100}; 
	while (startflag)
	{
		Sleep(100);
	    
		SetConsoleColor(FOREGROUND_GREEN); 
		g_nNum[0]++;
		g_nNum[1]++;
		printf("线程安全队列1载入%d\n", g_nNum[0]); 
   		printf("线程安全队列2载入%d\n", g_nNum[1]);
		SetConsoleColor(FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);  
		CmtWriteTSQData (g_timerQueueHdl, g_nNum, 2, TSQ_INFINITE_TIMEOUT,NULL);
		Sleep(0);
	}
    return 0;  
}

int CVICALLBACK ThreadFunction1 (void *functionData)
{
    long	   g_nNum1[2];
	while (startflag1)
	{
		Sleep(100);
		CmtReadTSQData (g_timerQueueHdl, g_nNum1, 2,TSQ_INFINITE_TIMEOUT, 0);
		printf("线程安全队列1读取%d\n", g_nNum1[0]); 
   		printf("线程安全队列2读取%d\n", g_nNum1[1]);
		Sleep(0);
	}
    return 0;  
}

CVI多线程数据保护(安全队列)_第1张图片

你可能感兴趣的:(CVI编程,cvi,多线程,线程安全队列)