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()
6void *myThreadFun(void *vargp) {
7 for (int i = 0; i < 10; i++) {
8 printf("Hello World! %d Printing from spawned thread\n", i);
9 sleep(1);
10 }
11 return NULL;
12}
13
14int 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 thread\n", i);
22 sleep(2);
23 }
24 pthread_join(thread_id, NULL);
25 exit(0);
26}
1package main
2
3import (
4 "fmt"
5 "time"
6)
7
8func 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 thread\n", 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 thread\n", i)
21 }
22}
1#include <iostream>
2#include <thread>
3#include <chrono>
4
5using namespace std;
6
7int 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}
1use std::thread;
2use std::time::Duration;
3
4fn 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}