Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <pthread.h>
- #include <string.h>
- #define MAX_MESSAGE_LENGTH 256
- // Define the struct Thread
- struct Thread {
- pthread_t id;
- int i;
- char message[MAX_MESSAGE_LENGTH];
- };
- // Function to be executed by each thread
- void* thread_function(void* arg) {
- struct Thread* thread_data = (struct Thread*)arg;
- // Create the message
- snprintf(thread_data->message, MAX_MESSAGE_LENGTH, "Hello from thread %d", thread_data->i);
- // Output the ID and message
- printf("Thread %d: %s\n", thread_data->i, thread_data->message);
- return NULL;
- }
- int main(int argc, char* argv[]) {
- if (argc != 2) {
- printf("Usage: %s <number_of_threads>\n", argv[0]);
- return 1;
- }
- int n = atoi(argv[1]);
- if (n <= 0) {
- printf("Please provide a positive number of threads.\n");
- return 1;
- }
- struct Thread threads[n];
- for (int i = 0; i < n; i++) {
- threads[i].i = i;
- printf("Thread %d is created\n", i);
- if (pthread_create(&threads[i].id, NULL, thread_function, &threads[i]) != 0) {
- perror("pthread_create");
- return 1;
- }
- }
- // Wait for all threads to finish
- for (int i = 0; i < n; i++) {
- pthread_join(threads[i].id, NULL);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement