C run function in new thread
In C, you can use the pthread
library to create a new thread that runs a function. Here's an example:
#include <pthread.h>
#include <stdio.h>
void* my_thread_function(void* arg) {
printf("Hello from new thread!\n");
return NULL;
}
int main() {
pthread_t thread;
int ret;
// Create a new thread
ret = pthread_create(&thread, NULL, my_thread_function, NULL);
if (ret!= 0) {
perror("pthread_create");
return 1;
}
// Wait for the thread to finish
pthread_join(thread, NULL);
return 0;
}
In this example, we define a function my_thread_function
that will be executed by the new thread. We then create a new thread using pthread_create
, passing the address of the function to be executed, as well as any arguments that the function may need.
The pthread_create
function returns a thread ID, which we store in the thread
variable. We can then use this thread ID to wait for the thread to finish using pthread_join
.
Note that the my_thread_function
function returns a void*
value, which is the return value of the thread. In this case, we return NULL
, but you can return any value that makes sense for your application.
Also, keep in mind that the pthread
library is not part of the standard C library, so you may need to link against a library that provides the pthread
functions, such as libpthread
on Linux.
Alternatively, you can use the std::thread
class from the C++ standard library to create a new thread. Here's an example:
#include <thread>
#include <iostream>
void my_thread_function() {
std::cout << "Hello from new thread!\n";
}
int main() {
std::thread t(my_thread_function);
// Wait for the thread to finish
t.join();
return 0;
}
This example is similar to the previous one, but uses the std::thread
class instead of pthread_create
. The std::thread
class provides a more convenient and type-safe way to create and manage threads.