Skip to content

Instantly share code, notes, and snippets.

@mkakh
Created June 30, 2024 01:24
Show Gist options
  • Save mkakh/857b600d593f255fef70e3e098e438f0 to your computer and use it in GitHub Desktop.
Save mkakh/857b600d593f255fef70e3e098e438f0 to your computer and use it in GitHub Desktop.
const N: usize = 100;
use libc::{c_void, pthread_attr_t, pthread_create, pthread_t};
use std::ptr;
extern "C" fn thread_func(arg: *mut c_void) -> *mut c_void {
let tid = unsafe { Box::from_raw(arg as *mut u32) };
println!("thread {tid} is started");
ptr::null_mut()
}
fn main() {
let mut threads: [pthread_t; N] = [0; N];
let attr: *const pthread_attr_t = ptr::null();
for (i, thread) in threads.iter_mut().enumerate() {
let tid_ptr = Box::into_raw(Box::new(i as u32)) as *mut c_void;
unsafe {
if pthread_create(thread, attr, thread_func, tid_ptr) != 0 {
eprintln!("Failed to create thread");
} else {
println!("Thread created successfully");
}
}
}
for thread in threads.into_iter() {
unsafe {
libc::pthread_join(thread, ptr::null_mut());
}
}
println!("Hello, world!");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment