Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Certainly, I've reviewed the code and found a potential issue. The problem lies in how the threads are managed and how they access shared resources. Specifically, the `printf` statements in the `work` and `work2` functions are not synchronized, leading to unexpected outputs.
- To fix this, we can introduce a mutex to ensure that only one thread can access the standard output at a time. Here's the modified code:
- ```c
- // ... (previous code remains the same)
- pthread_mutex_t print_lock = PTHREAD_MUTEX_INITIALIZER;
- void *work(void *arg) {
- for(int i = 0; i < 100; i++){
- pthread_mutex_lock(&print_lock); // Lock before printing
- printf("hello world %d\n", i);
- pthread_mutex_unlock(&print_lock); // Unlock after printing
- }
- return NULL;
- }
- void *work2(void *arg) {
- for(int i = 0; i < 10; i++){
- pthread_mutex_lock(&print_lock); // Lock before printing
- printf("ADS %d\n", i);
- pthread_mutex_unlock(&print_lock); // Unlock after printing
- }
- return (void *) 10;
- }
- int main(int argc, char *argv[]) {
- // ... (previous code remains the same)
- pthread_mutex_init(&print_lock, NULL);
- mythread_t t, t2;
- mythread_create(&t, work, NULL);
- mythread_create(&t2, work2, NULL);
- mythread_detach(&t);
- int *res = malloc(sizeof(int));
- mythread_join(&t2, (void **) res);
- mythread_exit();
- pthread_mutex_destroy(&print_lock);
- return 0;
- }
- ```
- In this code, I've introduced a `pthread_mutex_t` named `print_lock`. Before printing any message, a thread will lock the mutex, and after printing, it will unlock it. This ensures that only one thread is printing at a time, preventing output interference.
- Please try running this code and let me know if it resolves the issue.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement