类内使用CreateThread的问题
我想在类内调用一个函数,该函数单独使用一个线程类处理;但发现无法使用类内的函数,不知道大家都是怎么处理的。本人很想让这个线程和其他函数处理一样,保留类的封装性质,只能访问该对象的数据结构;
另个问题是我使用了一个静态的变量和函数,一个MyThread中创建一个线程处理,处理函数是前面的静态函数
// MyThread.h: interface for the MyThread class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_MYTHREAD_H__F33A4E09_FE1A_4D17_AE1D_C50F38C008F6__INCLUDED_)
#define AFX_MYTHREAD_H__F33A4E09_FE1A_4D17_AE1D_C50F38C008F6__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "Windows.h"
#include<iostream>
using namespace std;
static int i;
static DWORD WINAPI func(LPVOID mParam)
{
i=0;
while(true)
{
Sleep(1000);
//cout<<i<<endl;
i++;
}
return 0;
}
class MyThread
{
public:
bool BeginThread();
MyThread();
virtual ~MyThread();
private:
PROCESS_INFORMATION pi;
};
#endif // !defined(AFX_MYTHREAD_H__F33A4E09_FE1A_4D17_AE1D_C50F38C008F6__INCLUDED_)
// MyThread.cpp: implementation of the MyThread class.
//
//////////////////////////////////////////////////////////////////////
#include "MyThread.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
MyThread::MyThread()
{
}
MyThread::~MyThread()
{
}
bool MyThread::BeginThread()
{
unsigned long temp;
pi.hThread = CreateThread(NULL,0,func,NULL,0,&temp);
return true;
}
主函数
#include "MyThread.h"
int main()
{
MyThread m_Thread;
m_Thread.BeginThread();
while(true)
{
Sleep(1000);
cout<<i<<endl;
}
return 0;
}
但发现变量i显示的不正常,都是0;
如果直接在线程中显示是正常的;
请大家帮帮忙