Answers for "simple multithreaded hello world"

C++
0

simple multithreaded hello world

#include <unistd.h>  
#include <pthread.h>

// A C function that is executed as a thread
// when its name is specified in pthread_create()
void *myThreadFun(void *vargp) {
    for (int i = 0; i < 10; i++) {
        printf("Hello World! %d Printing from spawned thread\n", i);
        sleep(1);
    }
    return NULL;
}

int main() {
    // Create a new thread
    pthread_t thread_id;
    pthread_create(&thread_id, NULL, myThreadFun, NULL);

    // Main thread
    for (int i = 0; i < 10; i++) {
        printf("Hello World! %d from the main thread\n", i);
        sleep(2);
    }
    pthread_join(thread_id, NULL);
    exit(0);
}
Posted by: Guest on June-21-2021
0

simple multithreaded hello world

package main

import (
    "fmt"
    "time"
)

func main() {
    // Create a new thread
    go func() {
        for i := 1; i < 10; i++ {
            fmt.Printf("Hello World! %d. Printing from spawned thread\n", i);
            time.Sleep(1 * time.Millisecond)
        }        
    }()

    // Main thread    
    for i := 1; i < 10; i++ {
        time.Sleep(2 * time.Millisecond)
        fmt.Printf("Hello World! %d from the main thread\n", i)    
    }
}
Posted by: Guest on June-19-2021
0

simple multithreaded hello world

#include <iostream>
#include <thread>
#include <chrono>

using namespace std;

int main() {
    // Create a new thread
    auto f = [](int x) {
        for (int i = 0; i < x; i++) {
            cout << "Hello World! " << i << " Printing from spawned thread" << endl;
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
        }
    };
    thread th1(f, 10);

    // Main thread
     for (int i = 0; i < 10; i++) {
        cout << "Hello World! " << i << " from the main thread" << endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    }
    // Wait for thread th1 to finish
    th1.join();
    return 0;
}
Posted by: Guest on June-21-2021
0

simple multithreaded hello world

use std::thread;
use std::time::Duration;

fn main() {
    // Create a new thread
    let handle = thread::spawn(|| {
        for i in 1..10 {
            println!("Hello World! {}. Printing from spawned thread", i);
            thread:: sleep(Duration::from_millis(1)); 
        }
    });

    // Main thread
    for i in 1..10 {
        println!("Hello World! {} from the main thread", i);
        thread::sleep(Duration::from_millis(2));
    }

    // Hold the main thread until the spawned thread has completed
    handle.join().unwrap();
}
Posted by: Guest on June-19-2021

Code answers related to "simple multithreaded hello world"

Browse Popular Code Answers by Language