`

Chapter 8 Thread Synchronization in User Mode

阅读更多

做了个小程序,用来验证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);
}
 
  • 大小: 10.7 KB
  • 大小: 11.2 KB
0
0
分享到:
评论

相关推荐

    CLR via C# 3rd Edition

    全新的一章,讨论了类库和线程安全、primitive user-mode、kernel-mode构造和data alignment。 Chapter 29-Hybrid Thread Synchronization Constructs 全新的一章,讨论了不同的混合构造,如ManualResetEventSlim...

    UNIX环境高级编程(第二版,英文版)

    Chapter 8. Process Control Section 8.1. Introduction Section 8.2. Process Identifiers Section 8.3. fork Function Section 8.4. vfork Function Section 8.5. exit Functions ...

    UNIX环境高级编程英文第三版+源码

    Chapter 8. Process Control 227 8.1 Introduction 227 www.it-ebooks.info Contents xiii 8.2 Process Identifiers 227 8.3 fork Function 229 8.4 vfork Function 234 8.5 exit Functions 236 8.6 wait and ...

    Python Cookbook, 2nd Edition

    Interpolating Variables in a Stringin Python 2.4 Recipe 1.18. Replacing Multiple Patterns in a Single Pass Recipe 1.19. Checking a String for Any of Multiple Endings Recipe 1.20. Handling ...

    微软内部资料-SQL性能优化2

    System space can only be accessed while in kernel mode, while user space is accessible in user mode. This protects system space from being tampered with by user mode code. Shared System Space ...

    微软内部资料-SQL性能优化3

    The code shown in the slide represents how the lock mode is stored internally. You can see these codes by querying the master.dbo.spt_values table: SELECT * FROM master.dbo.spt_values WHERE type = N'L...

Global site tag (gtag.js) - Google Analytics