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)
}
}
0
0
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!
0
0
0
0
#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!
0
0
0
8
#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!
8
0
Are there any code examples left?
New code examples in category Go
-
Go 2022-03-27 22:30:23 golang check if ip is v6
-
Go 2022-03-27 16:20:18 make image go to center of page
-
Go 2022-03-24 15:20:01 why does my discord bot not work when i take code from googl
-
Go 2022-03-21 18:40:22 pass method as props vue
-
Go 2022-03-19 23:40:33 reverse a string in golang
-
Go 2022-03-18 12:45:06 golang while loop
-
Go 2022-03-17 19:30:08 instancing in godot
-
Go 2022-03-17 09:55:17 brew upgrae golang-migrate
-
Go 2022-03-17 06:15:06 Tushar Jadhav
-
Go 2022-03-17 00:00:12 golang cwd