112k views
2 votes
Create a c code, name it thread. Your code should use a loop to create 10 threads. All 10 threads will use the same function, but each thread will print its unique "ID". You can pass an "ID" as a parameter when creating the threads.

User HeroCC
by
7.6k points

2 Answers

2 votes
#include
#include

// Function that each thread will run
void *printID(void *id) {
int threadID = *((int *)id);
printf("Thread ID: %d\\", threadID);
pthread_exit(NULL);
}

int main() {
pthread_t threads[10];
int threadIDs[10];

// Create 10 threads
for (int i = 0; i < 10; ++i) {
threadIDs[i] = i + 1; // Unique ID for each thread
if (pthread_create(&threads[i], NULL, printID, (void *)&threadIDs[i]) != 0) {
fprintf(stderr, "Error creating thread %d\\", i + 1);
return 1; // Exit with an error code
}
}

// Wait for all threads to finish
for (int i = 0; i < 10; ++i) {
pthread_join(threads[i], NULL);
}

return 0; // Exit successfully
}
User Antoni Gual Via
by
8.4k points
6 votes

Final answer:

To create 10 threads in C and print their unique IDs, you can use the pthread library. In this code, the function printID is the function every thread will run. Each thread prints its assigned ID.

Step-by-step explanation:

C Code to Create and Print IDs of 10 Threads

To create 10 threads in C and print their unique IDs, you can use the pthread library. Here's an example code:

#include <stdio.h>
#include <pthread.h>

void* printID(void* threadID) {
long tid = (long) threadID;
printf("Thread ID: %ld\\", tid);
pthread_exit(NULL);
}

int main() {
pthread_t threads[10];
int rc;
long t;

for (t = 0; t < 10; t++) {
rc = pthread_create(&threads[t], NULL, printID, (void*) t);
if (rc) {
printf("ERROR; return code from pthread_create() is %d\\", rc);
return -1;
}
}

pthread_exit(NULL);
}

In this code, the function printID is the function every thread will run. The threadID passed as a parameter to each thread represents its unique ID. The main function creates 10 threads using a loop, passing the t variable as the thread ID. Each thread then prints its assigned ID. Finally, the program exits.

User Joshua Peterson
by
8.9k points