问题很简单,但解决方案让我望而却步。我想调用两个函数并让它们同时运行(在单独的线程中),但我只能在之后void function1()
调用和void function2()
运行,而不是在期间运行。我为处理器 1 和 2 设置了线程关联(我有一个多核处理器,希望你也有一个)。
我看到一次只调用一个函数的方式仅仅是因为我得到了 only 的输出,function 1
而通常我会看到function 1
and的混合function 2
。
随意重新调整代码以使其工作,但请尽量保持原始方法与类中线程调用函数的方式保持不变。这是完整的代码。
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <stdio.h>
#include <iostream>
class thread_class
{
private:
public:
void function1()
{
for(int count = 0; count < 1000; count++)
std::cout<<"function 1"<<std::endl;
}
void function2()
{
for(int count = 0; count < 1000; count++)
std::cout<<"function 2"<<std::endl;
}
thread_class(){}
~thread_class(){}
DWORD_PTR WINAPI threadMain0()
{
function1();
return 0;
}
DWORD_PTR WINAPI threadMain1()
{
function2();
return 0;
}
void thread()
{
HANDLE *m_threads = NULL;
DWORD_PTR c = 2;
m_threads = new HANDLE[c];
DWORD_PTR i = 0;
DWORD_PTR m_id0 = 0;
DWORD_PTR m_mask0 = 1 << i;
m_threads[i] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)threadMain0(), (LPVOID)i, NULL, &m_id0);
SetThreadAffinityMask(m_threads[i], m_mask0);
wprintf(L"Creating Thread %d (0x%08x) Assigning to CPU 0x%08x\r\n", i, (LONG_PTR)m_threads[i], m_mask0);
i = 1;
DWORD_PTR m_id1 = 0;
DWORD_PTR m_mask1 = 1 << i;
m_threads[i] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)threadMain1(), (LPVOID)i, NULL, &m_id1);
SetThreadAffinityMask(m_threads[i], m_mask1);
wprintf(L"Creating Thread %d (0x%08x) Assigning to CPU 0x%08x\r\n", i, (LONG_PTR)m_threads[i], m_mask1);
}
};
int main()
{
thread_class* MAIN_THREADS;
MAIN_THREADS = new thread_class();
MAIN_THREADS->thread();
delete MAIN_THREADS;
return 0;
}
编辑:这是下面代码的略微修改版本,显示它没有并行运行。
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <stdio.h>
#include <iostream>
class thread_class
{
private:
public:
void function1()
{
int exit = 0;
while(exit == 0)
{
std::cout<<"enter 1 to exit:"<<std::endl;
std::cin>>exit;
};
}
void function2()
{
for(int count = 0; count < 1000; count++)
std::cout<<"function 2"<<std::endl;
}
thread_class(){}
~thread_class(){}
DWORD_PTR WINAPI threadMain0()
{
function1();
return 0;
}
DWORD_PTR WINAPI threadMain1()
{
function2();
return 0;
}
void thread()
{
HANDLE *m_threads = NULL;
DWORD_PTR c = 2;
m_threads = new HANDLE[c];
DWORD_PTR i = 0;
DWORD_PTR m_id0 = 0;
DWORD_PTR m_mask0 = 1 << i;
m_threads[i] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)threadMain0(), (LPVOID)i, NULL, &m_id0);
SetThreadAffinityMask(m_threads[i], m_mask0);
wprintf(L"Creating Thread %d (0x%08x) Assigning to CPU 0x%08x\r\n", i, (LONG_PTR)m_threads[i], m_mask0);
i = 1;
DWORD_PTR m_id1 = 0;
DWORD_PTR m_mask1 = 1 << i;
m_threads[i] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)threadMain1(), (LPVOID)i, NULL, &m_id1);
SetThreadAffinityMask(m_threads[i], m_mask1);
wprintf(L"Creating Thread %d (0x%08x) Assigning to CPU 0x%08x\r\n", i, (LONG_PTR)m_threads[i], m_mask1);
}
};
int main()
{
thread_class* MAIN_THREADS;
MAIN_THREADS = new thread_class();
MAIN_THREADS->thread();
delete MAIN_THREADS;
return 0;
}