参考之前ChatGPT提供的代码模板做的,本代码在Windows10上运行过:
#include <iostream>
#include <windows.h>
#include <time.h>
DWORD WINAPI Thread1(LPVOID lpParam) // 1号线程函数
{
while (1)
{
std::cout << "111111111111111111\n";
Sleep(2000);
}
}
DWORD WINAPI Thread2(LPVOID lpParam) // 2号线程函数
{
while (1)
{
std::cout << "222222222222222222\n";
Sleep(2000);
}
}
int main() {
HANDLE hThread1, hThread2;
DWORD threadId1, threadId2;
// Create the new thread
hThread1 = CreateThread(NULL, 0, Thread1, NULL, 0, &threadId1);
hThread2 = CreateThread(NULL, 0, Thread2, NULL, 0, &threadId2);
if ((hThread1 == NULL) || (hThread2 == NULL)) {
std::cerr << "Failed to create thread." << std::endl;
return 1;
}
SetThreadAffinityMask(hThread1, 1); // Set the thread affinity mask to the first processor
SetThreadAffinityMask(hThread2, 2); // Set the thread affinity mask to the second processor
// Wait for the thread to finish
DWORD waitResult1 = WaitForSingleObject(hThread1, INFINITE);
DWORD waitResult2 = WaitForSingleObject(hThread2, INFINITE);
if ((waitResult1 == WAIT_FAILED) || (waitResult2 == WAIT_FAILED))
{
std::cerr << "Failed to wait for thread." << std::endl;
return 1;
}
// Close the thread handle
CloseHandle(hThread1);
CloseHandle(hThread2);
return 0;
}
运行结果: