简体   繁体   中英

Multithreading in VS2010

I have a C++ DLL created in VS2010. This DLL is responsible for generating a report and sending it to a server. This DLL is called by an another application which actually creates the data. Since sending the file to a server takes some time so, I don't want the calling application to wait till the DLL is busy in sending the file to a server.

To deal with the above-mentioned issue, I want to assign the task of sending file to a server (just one small function) to a separate thread and do not want to wait for this thread to complete (otherwise no benefit).

while(UserShutDownTheApp)
{
    - Main App Gather Data 
    - Main App Call data management DLL and pass data to it
        - DataManagementDLL: Generate a Report
        - DataManagementDLL: Start a THREAD and Send report to Server by this THREAD. Do not wait for this THREAD to complete
    - Main App finishes this iteration and is going to enter into next iteration.    
}

Since, I do not have control on the main calling application, I can make modifications only inside the DLL. I am confused how should I implement this logic? I mean, what happens if the Thread has not completed the task of sending the file to the server and meanwhile the main calling application has already called this DLL the second time.

You should add a bit more logic to your DLL. First of all, the call to the DLL should not directly sends the data to the server, but queue the task (simply add all passed data to internal queue). The DLL can have internal worker thread which should be responsible for processing the queue of tasks.

How internal implementation and architecture should look like, depends on existing API (is it modifiable or not).

Hint - please take a look at DllMain() https://msdn.microsoft.com/en-us/library/windows/desktop/ms682583(v=vs.85).aspx - it should be helpful as an entry point.

it is not clear all your constraint but this is a simple example to use threads in c++:

void sendreport(std::string data)
{
    std::cout << "send " << data;
    std::this_thread::sleep_for(std::chrono::seconds(10));

}

std::queue<std::thread> jobs;

void addjob(std::string data)
{
    while (jobs.size() > 10)
    {
        jobs.front().join();
        jobs.pop();
    }

    jobs.emplace(sendreport, data);
}

void waitalljobs()
{
    while (jobs.size() > 0)
    {
        jobs.front().join();
        jobs.pop();
    }
}


int main()
{

    addjob("first");
    addjob("second");
    waitalljobs();
}

In this sample I use a queue and I limit the number of current thread to 10. At the termination of the program waitalljobs wait for all thread had finished their works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM