做了个小程序,用来验证Interlocked的效果:
上图分别是注释掉“标记1”和“标记2”后的截图,和取消注释后的截图,下面是代码:
#include <windows.h>
#include <stdio.h>
#include <float.h>
#include <process.h>
#include <conio.h>
#include <iostream>
#include <tchar.h>
using namespace std;
LONG g = 0, flag = 0, T = 1, F = 0;
void threadfun1(void *pNull);
void threadfun2(void *pNull);
int main()
{
TCHAR szBuf[10240] = {0};// = TEXT("Thread Interlocked Experiment BEGIN!!!\n");
HANDLE harr[2];
harr[0] = (HANDLE)_beginthread(threadfun1, 0, szBuf);
harr[1] = (HANDLE)_beginthread(threadfun2, 0, szBuf);
// 如果不等两个线程结束,则极有可能主函数结束了,而那两个线程没结束!;
// 也就是说,屏幕上将无任何输出!;
WaitForMultipleObjects(2, harr, TRUE, INFINITE);
_tprintf(szBuf);
printf("%d\n", g);
getch();
return 0;
}
void threadfun1(void *pNull)
{
// 标记1
while (InterlockedExchange(&flag, T) == T)
;
g++;
int i, len, j;
TCHAR *pStr = (TCHAR*)pNull;
for (i = 0; i < 10; ++i)
{
for (j = 0; j < 10; ++j)
{
len = lstrlen(pStr);
pStr[len++] = '1';
pStr[len] = 0;
}
len = lstrlen(pStr);
pStr[len++] = '\n';
pStr[len] = 0;
Sleep(10); // 这样使实验的效果更明显;
}
InterlockedExchange(&flag, F);
}
void threadfun2(void *pNull)
{
// 标记2
while(InterlockedExchange(&flag, T) == T)
;
g++;
int i, len, j;
TCHAR *pStr = (TCHAR*)pNull;
for (i = 0; i < 10; ++i)
{
for (j = 0; j < 10; ++j)
{
len = lstrlen(pStr);
pStr[len++] = '2';
pStr[len] = 0;
}
len = lstrlen(pStr);
pStr[len++] = '\n';
pStr[len] = 0;
Sleep(10);
}
InterlockedExchange(&flag, F);
}
分享到:
相关推荐
Thread Synchronization in User Mode, OS programming.
操作系统概念英文课件:Chapter 6 Process Synchronization.ppt
操作系统英文教学课件:Chapter 6 Process Synchronization.ppt
博客“C#多线程——线程同步”的示例代码,关于多线程之线程同步,可参阅博客。
Absimcf-User identification must be done in speech information hiding. To shorten the time of building link and exchanging protocol, this paper presents a technology for fast cross-identification. To ...
操作系统概念英文课件:Chapter 6 Process Synchronization (2).ppt
This book applies techniques from distributed cooperative control of multi-agent dynamical systems to synchronization, power sharing, and load balancing problems arising in AC and DC electric power ...
Linux 和 Windows 线程同步的差别和使用的函数,含代码示例
让你更了解Thread Synchronization
Adaptive pinning control of cluster synchronization in complex networks with Lurie-type nonlinear dynamics
介绍时间同步协议和模型的英文原版书 包括各种典型协议和模型
CHAPTER 8 Thread Synchronization 259 CHAPTER 9 Locking, Performance, and NT6 Enhancements 301 CHAPTER 10 Advanced Thread Synchronization 335 CHAPTER 11 Interprocess Communication 379 CHAPTER 12 ...
复杂网络上的部分同步,敖滨,郑志刚,本文研究了规则网络加上少量非局域连接后所导致的部分同步,并从理论上给出了出现部分同步的条件和判据。
Synchronization_and_Arbitration_in_Digital_Systems
Distributed synchronization in wireless networks 是一篇很经典的讲述分布式同步的IEEE文章, 这是我对这篇文献阅读后总结的笔记,内有很多个人对文献的独到理解 作者:RayGoodwill 单位:桂林电子科技大学
Carrier and Bit Synchronization in Data Communication 通信过程中最重要的就是同步,这是篇经典的论文 Absrmcr-This paper examines the problems of carrier phase estimation and symbol timing estimation for...
操作系统概念英文课件:Chapter 06-process synchronization.pptx