CodexBloom - Programming Q&A Platform

GCC 12.2.0 scenarios to Compile C Code with Pthread and Inline Assembly for Lock-Free Structures

šŸ‘€ Views: 17 šŸ’¬ Answers: 1 šŸ“… Created: 2025-06-07
gcc inline-assembly pthread lock-free C

This might be a silly question, but I'm working with a compilation scenario with GCC 12.2.0 when trying to compile a C program that uses pthreads and incorporates inline assembly to implement a lock-free data structure. The specific behavior I'm getting is: ``` behavior: unexpected token in inline assembly ``` Here's a simplified example of my code: ```c #include <stdio.h> #include <pthread.h> typedef struct { volatile int value; } atomic_int; void atomic_increment(atomic_int* atom) { __asm__ __volatile__ ( "lock; xadd %0, %1" : "=r" (atom->value) : "m" (atom->value), "r" (1) : "cc" ); } void* thread_function(void* arg) { atomic_int* atom = (atomic_int*)arg; for (int i = 0; i < 1000000; ++i) { atomic_increment(atom); } return NULL; } int main() { atomic_int atom = {0}; pthread_t threads[4]; for (int i = 0; i < 4; ++i) { pthread_create(&threads[i], NULL, thread_function, &atom); } for (int i = 0; i < 4; ++i) { pthread_join(threads[i], NULL); } printf("Final Value: %d\n", atom.value); return 0; } ``` I've tried changing the inline assembly syntax and using different constraints, but nothing seems to work. Additionally, when I remove the inline assembly and use a simple atomic operation with `__sync_fetch_and_add`, it compiles successfully, but I'm looking for the performance benefits of the inline assembly approach. Could this be related to the way GCC handles inline assembly in conjunction with the volatile keyword, or is there perhaps a syntax scenario with my assembly code? I've also confirmed that my target architecture supports the instructions I’m using. Any guidance on how to resolve this would be appreciated! My development environment is Ubuntu. Any ideas what could be causing this? This is part of a larger CLI tool I'm building. Am I missing something obvious?