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)
}
}
3.67
10
#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);
}
Thank you!
10
0
4.43
7
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();
}
Thank you!
7
0
4.22
9
#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;
}
Thank you!
9
0
Are there any code examples left?
New code examples in category Rust
-
Rust 2022-03-27 22:00:04 rust print i8
-
Rust 2022-03-27 14:15:02 rust check if key in hashmap
-
Rust 2022-03-22 13:45:18 rust convert a string (with decimals) to a floating point number.
-
Rust 2022-03-11 20:00:15 creating constants in rust
-
Rust 2022-03-07 01:55:02 hello world in rust
-
Rust 2022-03-03 20:10:04 levenshtein distance
-
Rust 2022-02-24 12:40:24 execution duration
-
Rust 2022-02-20 05:45:02 matching in rust
-
Rust 2022-02-19 17:35:12 rust bitset stack
-
Rust 2022-01-30 18:30:40 rust compile and run