Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- To synchronize access to the standard output without using `pthread_mutex`, you can use atomic operations. In this case, we can use `__sync_lock_test_and_set` and `__sync_synchronize` for a simple lock.
- Here's the modified code:
- ```c
- // ... (previous code remains the same)
- volatile int print_lock = 0;
- void *work(void *arg) {
- for(int i = 0; i < 100; i++){
- while (__sync_lock_test_and_set(&print_lock, 1)); // Attempt to acquire lock
- printf("hello world %d\n", i);
- __sync_synchronize(); // Ensure the printf completes before releasing lock
- print_lock = 0; // Release lock
- }
- return NULL;
- }
- void *work2(void *arg) {
- for(int i = 0; i < 10; i++){
- while (__sync_lock_test_and_set(&print_lock, 1)); // Attempt to acquire lock
- printf("ADS %d\n", i);
- __sync_synchronize(); // Ensure the printf completes before releasing lock
- print_lock = 0; // Release lock
- }
- return (void *) 10;
- }
- int main(int argc, char *argv[]) {
- // ... (previous code remains the same)
- 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();
- return 0;
- }
- ```
- In this code, we use `__sync_lock_test_and_set` to attempt to acquire the lock. If the lock is already held (`print_lock == 1`), the thread will spin in a loop until it can acquire the lock. After printing, we use `__sync_synchronize` to ensure that the `printf` completes before releasing the lock.
- Please try running this code and let me know if it resolves the issue.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement