Untitled
unknown
c_cpp
a year ago
1.1 kB
6
Indexable
#include <stdio.h>
#include <pthread.h>
char *global_ptr;
int global_cnt = 0;
struct thread_args {
long thread_id;
int *stack_var;
};
void *thread_function(void *arg) {
struct thread_args *args = (struct thread_args *)arg;
printf("Thread %ld: Stack variable from main = %d\n",
args->thread_id, *(args->stack_var));
printf("Thread %ld: Global string = %s\n",
args->thread_id, global_ptr);
global_cnt++;
return NULL;
}
int main() {
pthread_t threads[2];
struct thread_args args[2];
int main_stack_var = 42;
global_ptr = "Hello from main thread";
for(int i = 0; i < 2; i++) {
args[i].thread_id = i + 1;
args[i].stack_var = &main_stack_var;
if(pthread_create(&threads[i], NULL, thread_function, &args[i]) != 0) {
printf("Error creating thread %d\n", i);
return 1;
}
}
for(int i = 0; i < 2; i++) {
pthread_join(threads[i], NULL);
}
printf("Main thread: Final global counter = %d\n", global_cnt);
return 0;
}Editor is loading...
Leave a Comment