Hi there...
I'm new to this forum so please correct me if this is not the right place to post this...
I have created two threads in the following code, and was expecting the threads to behave quite differently than they actually did...
can someone please explain why this happens? I'd be more than grateful.
Code:
DWORD ThreadFunc(LPVOID p)
{
int n;
n = *(int *)p;
for (int i=0; i<5; i++)
{
printf("%d\n", n);
sleep(10);
}
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
int n=2;
printf("Two Threads\n");
HANDLE hThread = CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)ThreadFunc, (LPVOID)&n, NULL, NULL);
// CloseHandle(hThread);
for (int i = 0; i<5; i++)
{
printf("----1\n");
sleep(10);
}
WaitForSingleObject(hThread,INFINITE);
char ch = getchar();
return 0;
}
Why does the program output look like this?
Thanks in advance.
what I was expecting was actually the first example.
I still don't quite understand why I get a different output every time,
and more importantly why the threads are not synced,
My next question, is a little more complex.
How come the number of times the threads print to screen is different
when I test this with different operating systems?
btw, i fixed a few places there should be S instead of s.
Code:
#include "stdafx.h"
#include "windows.h"
#include "stdio.h"
DWORD ThreadFunc(LPVOID p)
{
int n;
n = *(int *)p;
for (int i=0; i<5; i++)
{
printf("%d\n", n);
Sleep(10);
}
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
int n=2;
printf("Two Threads\n");
HANDLE hThread = CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)ThreadFunc, (LPVOID)&n, NULL, NULL);
CloseHandle(hThread);
for (int i = 0; i<5; i++)
{
printf("----1\n");
Sleep(10);
}
WaitForSingleObject(hThread,INFINITE);
char ch = getchar();
return 0;
}
>> btw, i fixed a few places...
But you didn't fix the error from post #3.
>> ... is different when I test this with different operating systems?
If you have code for some non-MS OS, then you will need to post that code as well.
by different OS i mean windows XP, 2000, and 7... they all give different amount of output lines.
I think this has something to do with the Windows Scheduler.
Does some1 know anything about this?
Windows is a pre-emptive multitasking operating system and its scheduler will schedule threads as it sees fit.
As such, you should never assume that threads will get executed in any sort of order.
As a programmer new to coding m/t applicationd, please read the previous sentence again because it is that important.
If you do need threads to be run in a particular order, then you need to control the order of execution via synchronization objects (e.g. critical sections, mutexes, events, and so on).
Bookmarks