【发布时间】:2018-08-31 19:13:32
【问题描述】:
您好,我有一个应用程序使用一个线程将缓冲区从*src 复制到*dst,但我希望在程序开始时启动线程。当我想使用线程时,我想将*src、*dst 和size 传递给线程,以便它可以开始复制缓冲区。我该如何做到这一点?因为当我启动一个线程时,我会在实例化对象时传递值,ThreadX 在创建线程时传递。
Thread^ t0 = gcnew Thread(gcnew ThreadStart(gcnew ThreadX(output, input, size), &ThreadX::ThreadEntryPoint));
总结一下我想这样做:
- 程序开始
- 创建一个线程
- 在线程中等待
- 传递参数并唤醒线程开始复制
- 在线程中完成复制后,让主线程知道它已完成
- 就在程序结束之前加入线程
示例代码如下所示。
谢谢!
#include "stdafx.h"
#include <iostream>
#if 1
using namespace System;
using namespace System::Diagnostics;
using namespace System::Runtime::InteropServices;
using namespace System::Threading;
public ref class ThreadX
{
unsigned short* destination;
unsigned short* source;
unsigned int num;
public:
ThreadX(unsigned short* dstPtr, unsigned short* srcPtr, unsigned int size)
{
destination = dstPtr;
source = srcPtr;
num = size;
}
void ThreadEntryPoint()
{
memcpy(destination, source, sizeof(unsigned short)*num);
}
};
int main()
{
int size = 5056 * 2960 * 10; //iris 15 size
unsigned short* input; //16bit
unsigned short* output;
Stopwatch^ sw = gcnew Stopwatch();
input = new unsigned short[size];
output = new unsigned short[size];
//elapsed time for each test
int sw0;
int sw1;
int sw2;
int sw3;
//initialize input
for (int i = 0; i < size; i++) { input[i] = i % 0xffff; }
//initialize output
for (int i = 0; i < size; i++) { output[i] = 0; }
// TEST 1 //////////////////////////////////////////////////////////////////////
for (int i = 0; i < size; i++) { output[i] = 0; }
//-----------------------------------------------------------------------
Thread^ t0 = gcnew Thread(gcnew ThreadStart(gcnew ThreadX(output, input, size), &ThreadX::ThreadEntryPoint));
t0->Name = "t1";
t0->Start();
t0->Join();
//-----------------------------------------------------------------------
return 0
}
【问题讨论】:
标签: c++ .net multithreading thread-safety c++-cli