I need help with running two function at the same time .
MultiThreading?

void Function1(int n)
{
while(n<10)
{
n++;
}
}
void Function2(int n)
{
while(n<20)
{
n++;
}
}

If these are the 2 functions,can someone tell me how I can start the 2 together from int main().I haven't been able to get it right from the internet.
Please type the code for this,if you can.

Dani AI

Generated

originally asked how to run two functions at the same time and, after asked about platform, confirmed Visual C++. Two concise, practical options for Visual C++ are shown below: prefer modern C++ std::thread when your compiler supports it; if not, use the CRT/WinAPI _beginthreadex approach.

#include <thread>

void taskA(int n) {
    while (n-- > 0) {
        // work
    }
}

void taskB(int n) {
    for (int i = 0; i < n; ++i) {
        // work
    }
}

int main() {
    std::thread t1(taskA, 10);
    std::thread t2(taskB, 20);

    // wait for both to finish
    t1.join();
    t2.join();
    return 0;
}

If your version of Visual C++ does not provide <thread>, use _beginthreadex to avoid CRT issues that can occur with CreateThread:

#include <process.h>
#include <windows.h>

unsigned __stdcall worker(void* arg) {
    int n = *static_cast<int*>(arg);
    // work
    return 0;
}

int main() {
    int a = 10, b = 20;
    uintptr_t h1 = _beginthreadex(NULL, 0, worker, &a, 0, NULL);
    uintptr_t h2 = _beginthreadex(NULL, 0, worker, &b, 0, NULL);

    WaitForSingleObject(reinterpret_cast<HANDLE>(h1), INFINITE);
    WaitForSingleObject(reinterpret_cast<HANDLE>(h2), INFINITE);

    CloseHandle(reinterpret_cast<HANDLE>(h1));
    CloseHandle(reinterpret_cast<HANDLE>(h2));
    return 0;
}

Quick tips: always join() (or otherwise ensure threads finish) unless detaching is intentional; protect shared data with std::mutex or atomics; avoid busy loops that hog the CPU (use sleeps or condition variables); do not call GUI APIs from worker threads. If <thread> is missing, update the toolset or use a threading library (e.g., Boost.Thread) for portable code.

Recommended Answers

All 2 Replies

>MultiThreading?
Multithreading, spawn multiple processes, or fake your own threading. The latter isn't recommended for real code, but it can be fun.

>Please type the code for this,if you can.
I'm not going to do your work for you, dude. You didn't even say what platform you're running on, which means any code you're given might not compile.


I'm not going to do your work for you, dude. You didn't even say what platform you're running on, which means any code you're given might not compile.

I am using visual c++.
This is not my final application,and I am only trying to learn the code concerned to these simple functions,so I can apply it elsewhere.
See if you can help me out. :S

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.