Do Thread A and B Require Mutex to Operate on High/Low of a DWORD?


Given a 32-bit DWORD, and two threads A and B, do they require Mutex (exclusive resources) to read/write the High/Low DWORD respectively? e.g. Thread A reads two low bytes of the DWORD and thread B writes two high bytes of the DWORD.

Given the following C++ compiled in Visual Studio.

#define DWORD	unsigned int
#define BYTE	unsigned char
int _tmain(int argc, _TCHAR* argv[])
{
	DWORD dwa;
	BYTE *pb;
	pb	= (BYTE *)&dwa;
	scanf("%d",&dwa);
	*pb	= (dwa & 0xFF) +5;
	printf("dwa=%d\r\n", dwa);
	return 0;
}

Under RELEASE mode, it will be compiled into something like this:

.text:00401013                 add     byte ptr [ebp+dwa], 5
.text:00401017                 mov     ecx, [ebp+dwa]
.text:0040101A                 push    ecx
.text:0040101B                 push    offset aDwaD    ; "dwa=%d\r\n"

From the assembly, it is obvious that the dwa takes four bytes but we use (BYTE*) which operates a single byte. Thus, the High RW thread do not interfere with the Low RW thread. You can just use two Mutex for the High 16-bit and Low 16-bit respectively.

How about the Delphi compilers?

procedure TForm1.Button1Click(Sender: TObject);
var
  dwa: DWORD;
  p: PBYTE;
begin
  dwa := strtoint(Edit1.text) ;
  p := @dwa;
  p^ := p^ + 10;
  memo1.Lines.add(inttostr(dwa));
end;

will be translated to:

Unit1.pas.34: p := @dwa;
00467AF3 8D45FC           lea eax,[ebp-$04]
Unit1.pas.35: p^ := p^ + 10;
00467AF6 80000A           add byte ptr [eax],$0a
Unit1.pas.36: memo1.Lines.add('dwa='+inttostr(dwa));
00467AF9 8B45FC           mov eax,[ebp-$04]

The byte ptr means only operate on a single byte. If we use PBYTE pointer to access the High/Low bytes, they are quite independent. The CPU minimal operating unit is byte. However, we would need two mutex, e.g. MutexHigh and MutexLow to protect the ThreadHigh and ThreadLow bytes.

–EOF (The Ultimate Computing & Technology Blog) —

370 words
Last Post: Simple Javascript Unit Testing
Next Post: How to Prevent Script Running from Browsers?

The Permanent URL is: Do Thread A and B Require Mutex to Operate on High/Low of a DWORD? (AMP Version)

Leave a Reply