In this article we will learn about some of the frequently asked GO programming questions in technical like “simple multithreaded hello world” Code Answer’s. When creating scripts and web applications, error handling is an important part. If your code lacks error checking code, your program may look very unprofessional and you may be open to security risks. Error or stack handling on go was simple and easy. An error message with filename, line number and a message describing the error is sent to the browser. This tutorial contains some of the most common error checking methods in GO. Below are some solution about “simple multithreaded hello world” Code Answer’s.
simple multithreaded hello world
xxxxxxxxxx
1
package main
2
3
import (
4
"fmt"
5
"time"
6
)
7
8
func main() {
9
// Create a new thread
10
go func() {
11
for i := 1; i < 10; i++ {
12
fmt.Printf("Hello World! %d. Printing from spawned threadn", i);
13
time.Sleep(1 * time.Millisecond)
14
}
15
}()
16
17
// Main thread
18
for i := 1; i < 10; i++ {
19
time.Sleep(2 * time.Millisecond)
20
fmt.Printf("Hello World! %d from the main threadn", i)
21
}
22
}
simple multithreaded hello world
xxxxxxxxxx
1
#include <iostream>
2
#include <thread>
3
#include <chrono>
4
5
using namespace std;
6
7
int main() {
8
// Create a new thread
9
auto f = [](int x) {
10
for (int i = 0; i < x; i++) {
11
cout << "Hello World! " << i << " Printing from spawned thread" << endl;
12
std::this_thread::sleep_for(std::chrono::milliseconds(500));
13
}
14
};
15
thread th1(f, 10);
16
17
// Main thread
18
for (int i = 0; i < 10; i++) {
19
cout << "Hello World! " << i << " from the main thread" << endl;
20
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
21
}
22
// Wait for thread th1 to finish
23
th1.join();
24
return 0;
25
}
simple multithreaded hello world
xxxxxxxxxx
1
use std::thread;
2
use std::time::Duration;
3
4
fn main() {
5
// Create a new thread
6
let handle = thread::spawn(|| {
7
for i in 1..10 {
8
println!("Hello World! {}. Printing from spawned thread", i);
9
thread:: sleep(Duration::from_millis(1));
10
}
11
});
12
13
// Main thread
14
for i in 1..10 {
15
println!("Hello World! {} from the main thread", i);
16
thread::sleep(Duration::from_millis(2));
17
}
18
19
// Hold the main thread until the spawned thread has completed
20
handle.join().unwrap();
21
}
simple multithreaded hello world
xxxxxxxxxx
1
#include <unistd.h>
2
#include <pthread.h>
3
4
// A C function that is executed as a thread
5
// when its name is specified in pthread_create()
6
void *myThreadFun(void *vargp) {
7
for (int i = 0; i < 10; i++) {
8
printf("Hello World! %d Printing from spawned threadn", i);
9
sleep(1);
10
}
11
return NULL;
12
}
13
14
int main() {
15
// Create a new thread
16
pthread_t thread_id;
17
pthread_create(&thread_id, NULL, myThreadFun, NULL);
18
19
// Main thread
20
for (int i = 0; i < 10; i++) {
21
printf("Hello World! %d from the main threadn", i);
22
sleep(2);
23
}
24
pthread_join(thread_id, NULL);
25
exit(0);
26
}