SetThreadAffinityMask() seems doesn't work if the thread function contain "printf()"

1k Views Asked by At

I have written a test program to bind a thread on a CPU.Here is my test code:

#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
DWORD WINAPI ThreadFunc(LPVOID pM) {
    while(1) {
        printf("Doesn't work anymore");   //If i add this printf function,the setthreadaffinitymask seems doesn't work anymore.Which u can see from two pictures i post.
    }
}
int main() 
{
    HANDLE h;
    DWORD_PTR RetFlag;
    h = CreateThread(NULL, 0, ThreadFunc, NULL, 0, NULL);
    if((RetFlag = SetThreadAffinityMask(h, 0x08)) == 0)
        printf("SetThreadAffinityMask fails\n");
    WaitForSingleObject(h, INFINITE);
    return 0;
}

CPU Rate Pic without printf()

CPU Rate Pic with printf()

And of course, the right result should be like pic one.But what's going on if i add printf() function in the thread function?Is there any trick i don't know?Thanks...

1

There are 1 best solutions below

1
On

I think that the affinity does work, but the issue here is that printf() writes some text (to the console?) and waits synchronously for the text to be written.

Now, this text has to be printed somewhere, and that somewhere is in charge of a different thread/process, it can even be real I/O to disk or network. That's why you see the drop in CPU usage of CPU3: it is idle waiting for that I/O to complete.