Voici un modèle typique:
1) Définir une structure de données qui encapsule toutes les données de votre fil a besoin 2) le thread principal, instancier une copie de la structure de données sur le tas en utilisant l'opérateur new. 3) Remplissez la structure de données, placez le pointeur sur void *, passez le void * à la procédure thread par tous les moyens qui vous sont fournis par votre bibliothèque de threads. 4) Lorsque le thread de travail obtient le void *, il le réinterprète_cast vers la structure de données, puis prend possession de l'objet. Ce qui signifie que lorsque le thread est fait avec les données, le thread le libère, par opposition au thread principal qui le désalloue.
Voici un exemple de code que vous pouvez compiler & test sous Windows.
#include "stdafx.h"
#include <windows.h>
#include <process.h>
struct ThreadData
{
HANDLE isRunning_;
};
DWORD WINAPI threadProc(void* v)
{
ThreadData* data = reinterpret_cast<ThreadData*>(v);
if(!data)
return 0;
// tell the main thread that we are up & running
SetEvent(data->isRunning_);
// do your work here...
return 1;
}
int main()
{
// must use heap-based allocation here so that we can transfer ownership
// of this ThreadData object to the worker thread. In other words,
// the threadProc() function will own & deallocate this resource when it's
// done with it.
ThreadData * data = new ThreadData;
data->isRunning_ = CreateEvent(0, 1, 0, 0);
// kick off the new thread, passing the thread data
DWORD id = 0;
HANDLE thread = CreateThread(0, 0, threadProc, reinterpret_cast<void*>(data), 0, &id);
// wait for the worker thread to get up & running
//
// in real code, you need to check the return value from WFSO and handle it acordingly.
// Here I assume the retval is WAIT_OBJECT_0, indicating that the data->isRunning_ event
// has become signaled
WaitForSingleObject(data->isRunning_,INFINITE);
// we're done, wait for the thread to die
WaitForSingleObject(thread, INFINITE);
CloseHandle(thread);
return 0;
}
Ha, la réponse Java a été acceptée à une question taggés C++ :) Ce –
est certainement pas la réponse à cette question –