C ++类模块中的多线程 [英] Multithreading in C++ Class Module

查看:80
本文介绍了C ++类模块中的多线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我在类MC_Simulation中发布了一个有关多线程的问题.我的问题是从静态线程函数访问类信息.显然,可以通过在参数中使用指向"this"的指针来解决此问题,该指针已转移到线程函数中.

Recently I have posted a question with regard to multithreading inside my class MC_Simulation. My problem was the access to class information from the static thread function. This problem is solved apparently by using the pointer to ‘this’ in the argument, which was transferred to the threading function.

// define the Thread Data Structure to be transferred to the (static) thread function
// --------------------------
typedef struct Thread_Data{
	MC_Simulation*	mc_simulation;	// this solved my initial problem
	long  first_scenario;
	long  last_scenario;
	char  bond_data_file[_MAX_FNAME];	
} THREAD_DATA, *PTHREAD_DATA;


不幸的是,我关于胎面功能的问题尚未最终解决.
出现了两个问题.

1)我的线程函数应该使用
编写计算结果


My problems with the tread function unfortunately are not yet finalized.
Two issues have shown up.

1) My thread function is supposed to write calculated results using

ofstream bond_data;
bond_data.open(FILE_NAME, ios::trunc);
// in between calculating some stuff
    // then output results
    bond_data <<  results << EL;
    bond_data.close();


这似乎无法正常工作.我必须改用fprinf(..)吗?

2)似乎还没有适当处理其他一些问题,例如线程同步,这在前面已得到明确解决.我不完全知道该怎么做.请看一下结构:


this does not seem to work properly. Do I have to use fprinf(..) instead?

2) It also seems that some other issues have not been dealt with properly such as synchronization of threads, which has been explicitly addressed earlier. I am not fully aware how to do that. Please have a look at the structure:

// -----------------------------------
// member function in MC_Simulation:

Void initiate_threads(void){

int 		scenario_range[MAX_THREADS+1];
HANDLE		hThread[MAX_THREADS]; 
DWORD		dwThreadID[MAX_THREADS];
PTHREAD_DATA	pthread_arg[MAX_THREADS];

/* initiate  threads, each thread is supposed to run a loop starting with first_scenario and ending with last_scenario and there are 10,000 scenarios in total */
for (int index=0; index<max_threads;index++){>

        // allocate memory
        pthread_arg[index] =	(PTHREAD_DATA) HeapAlloc(GetProcessHeap(), 
                                                 HEAP_ZERO_MEMORY,
                				 sizeof(THREAD_DATA));
	// fill the argument of thread function
	pthread_arg[index]->first_scenario = scenario_range[index];
	pthread_arg[index]->last_scenario  = scenario_range[index+1];		pthread_arg[index]->mc_simulation  = this;
        sprintf(pthread_arg[index]->bond_data_file,"%s_%d",bond_data_file,index);

        hThread[index] = CreateThread(NULL, 0, thread_function ,
                                      pthread_arg[index], 0, &dwThreadID[index]);		
	} // end for loop

	 // Wait until all threads have terminated.
       	WaitForMultipleObjects(MAX_THREADS, hThread, TRUE, INFINITE);

	  for(int i=0; i < MAX_THREADS; i++) {
			CloseHandle(hThread[i]);
			if(pthread_arg[i] != NULL){
	 			HeapFree(GetProcessHeap(), 0, pthread_arg[i]);
	 		pthread_arg[i] = NULL;}    // Ensure address is not reused.
	  } // end for loop

} // end thread calling function


我不确定我是否适当考虑了所有重要问题,例如线程同步.该例程未按预期执行. "thread_function"本身是一个嵌套循环,该循环跨越pthread_arg [index]中定义的场景间隔,然后跨越模拟路径内的各个周期,最后跨越固定收益投资组合的债券. 场景"和绑定"是单独的类,并且在库中同时调用链接的函数.我必须更改什么还是对多线程有太多期望?


I am not sure whether I have taken account of all important issues properly, such as synchronization of the threads. The routine is not performing as expected. "thread_function" on its own is a nested loop across the interval of scenarios as defined in pthread_arg[index], then across the periods within a simulation path, and finally across the bonds of a fixed income portfolio. "Scenario" and "Bond" are separate classes and calling simultaneously functions of a linked in library. What do I have to change or do I expect too much from multithreading anyway?

推荐答案

ofstream bond_data;
bond_data.open(FILE_NAME, ios::trunc);
// in between calculating some stuff
// then output results
bond_data <<  results << EL;
bond_data.close();


我假设FILE_NAME是一个常量,在这种情况下,您正在同时截断并从多个线程写入同一文件-听起来不是个好主意.

也许您打算使用Thread_Data结构的bond_data_file成员?

最好的问候
Espen Harlinn


I assume FILE_NAME is a constant, in which case you are truncating and writing to the same file from multiple threads concurently - that doesn''t sound like a good idea.

Perhaps you meant to use the bond_data_file member of the Thread_Data structure?

Best regards
Espen Harlinn


我不明白您的意思,这似乎无法正常工作".流运算符在线程中工作得很好.分配pthread内存有点复杂.查找信号量,事件,多线程队列,线程锁定等...创建线程时,可以将其传递给(void *).在此处传递类实例,您可以为每个线程关联一个类.然后在您的线程中,将(void *)转换回类类型并在类中调用方法.
I don''t know what you mean by, "this does not seem to work properly". Stream operators work just fine in threads. Allocating pthread memory is a bit complicated. Look up semaphores, events, multithreaded queues, thread locking etc... When you create a thread, you can pass it a (void *). Pass the class instance here, and you can associate one class for each thread. Then in your thread, cast that (void *) back to the class type and call methods in the class.


ofstream bond_data;
bond_data.open(pThreadArg->bond_data_file, ios::trunc);
// in between calculating some stuff
// then output results
bond_data <<  results << EL;
bond_data.close();


此处FILE_NAME更改为bond_data_file,因此将为每个线程创建单独的文件.


Here FILE_NAME is changed to bond_data_file, therefore separate files will be created for each threads.

sprintf(pthread_arg[index]->bond_data_file,"%s_%d",bond_data_file,index);


应该为bond_data_file分配输出文件名的开头.

我不确定我是否已经适当考虑了所有重要问题,例如线程的同步.

确保thread_func没有更新该类中的任何参数.由于我们正在将此指针(作为结构的mc_simulation参数)传递给线程.如果有多个线程更新该类的任何参数,则将创建访问冲突或不正确的结果.

该例程未按预期执行.

有什么问题?如果您的计算机是单核处理器,那么您将无法获得更好的性能.
如果一个线程的输入取决于其他线程的输出,那么您将无法获得预期的输出.请确保单个线程的处理是独立的,即,这些线程都不要求其他线程的输出.例如,thread_N的端口对开计算从first_calculation到last_calculation开始,并且它不应该依赖于任何线程的端口对开计算.


bond_data_file should be assigned starting of output file name.

I am not sure whether I have taken account of all important issues properly, such as synchronization of the threads.

Make sure thread_func is not updating any parameters in the class. Since we are passing this pointer(as mc_simulation parameter of the structure) to threads. If more than one thread updating any parameter of the class, it will create access violation or improper results.

The routine is not performing as expected.

What are the problems? If your machine is single core processor then you will not get a better performance.
If input of one thread is depend on the output of other threads, then you will not get the expected output. Please make sure processing of a single thread is independent, ie, none of these thread require an output from other thread. For example, Port Folio calculation of thread_N is started from first_calculation to last_calculation, and it should not depend on the Port Folio calculation of any thread.


这篇关于C ++类模块中的多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆