11. Addition of Two No's - CreateThread - Windows System Programming in C/C++

preview_player
Показать описание
In This Tutorial I have added two no's using CreateThread API function.

Рекомендации по теме
Комментарии
Автор

having problem with the execution of cout statements
their order is not correct also in your code "thread creation" gets printed before "addition: " why?

subscriber
Автор

Dude!! why you pass a if it is a global variable? Either you make it a global variable /*hence don't pass it to the function*/or make it a local variable and receive the parameter from ThreadFun then cast it to the suitable type.

lamyaa
Автор

i dont get it.. why do you pass argument to the thread, if a[] is global variable, if you would not pass the argument to the thread it still would work. would not it ?

daviddav
Автор

I am trying to use this code, however sometime it prints corrupted value. So for lets say I am passing address of variable "a" which is containing a value of 10. Sometime it prints the correct value which is 10, sometime 0 and sometime nothing. What the correct use of this ThreadProc ?

DWORD WINAPI ThreadFun(LPVOID lpParam)
{
DWORD* value = (DWORD*)lpParam;
printf_s("\n%ul", *value);
return 0;

}

sashaa
Автор

Call back function does the trick.

typedef int (*funcPtr)(int, int, int*);

struct DATA {
funcPtr cb;
void* b;
};

int add(int a, int b, int *c = 0) {

*c = a + b;
return 0;
}

DWORD WINAPI ThreadFunc(void* LpParam) {

((struct DATA*)LpParam)->cb(100, 200, (int*)((struct DATA*)LpParam)->b);
return 0;
}


void* createThread() {

HANDLE hThread;
DWORD ThreadID;
struct DATA d = {add, malloc(sizeof(int))};
hThread = CreateThread(NULL,
0,
ThreadFunc,
&d,
0,
&ThreadID);

if (hThread == NULL) {
return NULL;
}

//object will signaled when thread is terminated
WaitForSingleObject(hThread, INFINITE);
printf("%d \n", *(int*)d.b);
printf("main returned\n");
CloseHandle(hThread);
return &ThreadID;
}

sashaa
Автор

Sorry to say but the parameters are not being used, you are manipulating the global array which would work in any case even if parameters are not passed to the Thread Function. Make the global array int a[2], a local array within main() function and then pass the arguments by reference which is the only correct way of passing arguments to the thread.

AmeerHamza-fszh
Автор

Why you used (Void*)&a can you please explain it.

mallikarjunfp
Автор

Please do on CryptAcquireContextW, videos on Encryption decryption

mallikarjunfp
Автор

can u do finding the prime numbers from 1 to n using create threads function please

JUICZXXXX