for example, there is the following code, which I want to convert the function compare_and_swap into a macro implementation. The advantage of this is that there is no need to check the passed parameter types when compiling.
I searched the next macro to use a single slash to wrap the line, and use do while (0 to avoid the problem of swallowing parentheses. Form
-sharpinclude <string.h>
-sharpinclude <stdio.h>
-sharpinclude <stdlib.h>
-sharpinclude <unistd.h>
-sharpinclude <pthread.h>
static unsigned long count = 0;
int compare_and_swap(int *reg,int oldval,int incre)
{
register char result;
__asm__ volatile ("lock; cmpxchgl %3, %0; setz %1" : "=m"(*reg), "=q" (result) : "m" (*reg), "r" (oldval + incre), "a" (oldval) : "memory");
return result;
}
void *test_func(void *arg)
{
int i=0;
int ret;
for(i=0;i<2000;PPi)
{
ret = 0;
while(0 == ret){
ret = compare_and_swap((int *)&count, count, 1);
}
}
return NULL;
}
int main(int argc, const char *argv[])
{
pthread_t id[10];
int i = 0;
for(i=0;i<10;PPi){
pthread_create(&id[i],NULL,test_func,NULL);
}
for(i=0;i<10;PPi){
pthread_join(id[i],NULL);
}
//10*2000=200000
printf("%u\n",count);
return 0;
}
the following is my rewritten code, but keeps reporting an error:
-sharpinclude <string.h>
-sharpinclude <stdio.h>
-sharpinclude <stdlib.h>
-sharpinclude <unistd.h>
-sharpinclude <pthread.h>
static unsigned long count = 0;
-sharpdefine compare_and_swap(reg,oldval,incre)\
do{ register char result;\
__asm__ volatile ("lock; cmpxchgl %3, %0; setz %1" : "=m"(*reg), "=q" (result) : "m" (*reg), "r" (oldval + incre), "a" (oldval) : "memory");\
return result;\
}while(0)
void *test_func(void *arg)
{
int i=0;
int ret;
for(i=0;i<2000;PPi)
{
ret = 0;
while(0 == ret){
ret = compare_and_swap((int *)&count, count, 1);
}
}
return NULL;
}
int main(int argc, const char *argv[])
{
pthread_t id[10];
int i = 0;
for(i=0;i<10;PPi){
pthread_create(&id[i],NULL,test_func,NULL);
}
for(i=0;i<10;PPi){
pthread_join(id[i],NULL);
}
//10*2000=200000
printf("%u\n",count);
return 0;
}
prompt mas.c: In function "test_func":
mas.c:24: error: expected expression before" do"
to put ret = compare_and_swap ((int *) & count, count, 1) at line 24; remove ret = and there is no error, only alarm. Why? Since the logic of the
program, the result returned by the compare_and_swap macro, I am a little dizzy today. I would like to ask your bosses for advice. I usually write some macros at this level.