How to make function atomically? - locking

I am now practicing lock,semaphore,mutual exclusive ..
I trying to implements simple code such that add 1 iteratively using mutex.
And here is my code.
[A.c]
for(int i=0; i<1000;i++){
acquire(&lock);
ADD1("count.txt"); // count.txt is shared memory
temp=Load("count.txt") // Load func get number
printf("\n %d",temp);
release(&lock);
}
also there is [B.c] all the same with A.
And I compiled A.c and B.c
gcc A.c -o A
gcc B.c -o B
and execute
./A & ./B
what I expected is ascending printing such as
1
2
3
4
..
1999
2000
But there is problem, it correctly count until 2000
but.. it was not ascending order..
4
5
6
7
1
...
234
235
...
223
...
1999
2000
Think this is weird because If I can see '2000' then It means mutex lock does work!
But why printing log is not ascending order..?
p.s/ sorry for if you can't understanding well...
Since I used google translation, my bad

Related

gcov - how to reset the coverage statistics in the C/C++ code

This question is related to googletest - command line option to execute "the first, the second, etc"
I want to be able to attribute given coverage results to each googletest test case.
QUESTION
In my C++ code, is it possible to reset the statistics?
Every time a test-case is done executing, I would save the accumulated gcov statistics and reset them.
From within your C++ code you could try it with __gcov_dump and __gcov_reset. They are mentioned in the GNU documentation although there is surprisingly limited info on them.
Below is a C++ program main.cpp that calls both.
1 #include <iostream>
2 #include <signal.h>
3
4 extern "C" void __gcov_dump(void);
5 extern "C" void __gcov_reset(void);
6
7
8 static void handler(int signum)
9 {
10 std::cout<<std::endl<<"Signal "<<signum<<" received!"<<std::endl;
11 __gcov_dump(); // Dump coverage upon interupt
12 std::cout<<"Coverage data dumped!"<<std::endl;
13 exit(0);
14 }
15
16
17 int main()
18 {
19 // Initialize signal handling
20 struct sigaction sa;
21
22 sa.sa_handler = handler;
23 sigemptyset(&sa.sa_mask);
24 sa.sa_flags = SA_RESTART;
25
26 if (sigaction(SIGINT, &sa, NULL) == -1)
27 std::cerr<<"ERROR: Could not register handler"<<std::endl;
28
29 // Main loop
30 while(true) {
31 int n;
32 std::cout<<"Type a number: ";
33 std::cin>>n;
34
35 if (n % 2 == 0) {
36 std::cout<<"Your number is even!"<<std::endl;
37 }
38 else {
39 std::cout<<"Your number is odd!"<<std::endl;
40 }
41 __gcov_reset(); // Reset coverage at the end of every iteration
42 }
43 }
If I compile it with g++ main.cpp --coverage -O0 and then run it as follows:
gomfy:gcov$ ./a.out
Type a number: 1
Your number is odd!
Type a number: 2
Your number is even!
Type a number: 3
Your number is odd!
Type a number: 4
Your number is even!
Type a number: ^C
Signal 2 received!
Coverage data dumped!
And then call gcovr in the build directory, I get:
gomfy:gcov$ gcovr
------------------------------------------------------------------------------
GCC Code Coverage Report
Directory: .
------------------------------------------------------------------------------
File Lines Exec Cover Missing
------------------------------------------------------------------------------
main.cpp 18 6 33% 12-13,17,22-24,26-27,35-36,39,41
------------------------------------------------------------------------------
TOTAL 18 6 33%
------------------------------------------------------------------------------
This shows that the coverage has been successfully reset at the end of the while loop.

SQL dealing every bit without run query repeatedly

I have a column using bits to record status of every mission. The index of bits represents the number of mission while 1/0 indicates if this mission is successful and all bits are logically isolated although they are put together.
For instance: 1010 is stored in decimal means a user finished the 2nd and 4th mission successfully and the table looks like:
uid status
a 1100
b 1111
c 1001
d 0100
e 0011
Now I need to calculate: for every mission, how many users passed this mission. E.g.: for mission1: it's 0+1+1+0+1 = 5 while for mission2, it's 0+1+0+0+1 = 2.
I can use a formula FLOOR(status%POWER(10,n)/POWER(10,n-1)) to get the bit of every mission of every user, but actually this means I need to run my query by n times and now the status is 64-bit long...
Is there any elegant way to do this in one query? Any help is appreciated....
The obvious approach is to normalise your data:
uid mission status
a 1 0
a 2 0
a 3 1
a 4 1
b 1 1
b 2 1
b 3 1
b 4 1
c 1 1
c 2 0
c 3 0
c 4 1
d 1 0
d 2 0
d 3 1
d 4 0
e 1 1
e 2 1
e 3 0
e 4 0
Alternatively, you can store a bitwise integer (or just do what you're currently doing) and process the data in your application code (e.g. a bit of PHP)...
uid status
a 12
b 15
c 9
d 4
e 3
<?php
$input = 15; // value comes from a query
$missions = array(1,2,3,4); // not really necessary in this particular instance
for( $i=0; $i<4; $i++ ) {
$intbit = pow(2,$i);
if( $input & $intbit ) {
echo $missions[$i] . ' ';
}
}
?>
Outputs '1 2 3 4'
Just convert the value to a string, remove the '0's, and calculate the length. Assuming that the value really is a decimal:
select length(replace(cast(status as char), '0', '')) as num_missions as num_missions
from t;
Here is a db<>fiddle using MySQL. Note that the conversion to a string might look a little different in Hive, but the idea is the same.
If it is stored as an integer, you can use the the bin() function to convert an integer to a string. This is supported in both Hive and MySQL (the original tags on the question).
Bit fiddling in databases is usually a bad idea and suggests a poor data model. Your data should have one row per user and mission. Attempts at optimizing by stuffing things into bits may work sometimes in some programming languages, but rarely in SQL.

How to convert Stack based instructions to Register based

This is what I have tested with the dis module in python -
>>> def f():
... a = 1
... b = 2
... c = 3
... a = b + c * a
... return a + c
...
>>> dis.dis(f)
2 0 LOAD_CONST 1 (1)
2 STORE_FAST 0 (a)
3 4 LOAD_CONST 2 (2)
6 STORE_FAST 1 (b)
4 8 LOAD_CONST 3 (3)
10 STORE_FAST 2 (c)
5 12 LOAD_FAST 1 (b)
14 LOAD_FAST 2 (c)
16 LOAD_FAST 0 (a)
18 BINARY_MULTIPLY
20 BINARY_ADD
22 STORE_FAST 0 (a)
6 24 LOAD_FAST 0 (a)
26 LOAD_FAST 2 (c)
28 BINARY_ADD
30 RETURN_VALUE
Those are instructions for a stack-based virtual machine. Is there any way to convert the above stack-based instructions into register-based instructions provided I have access to unlimited number of registers.
I only know about one tool which does that, we know that JVM is stack based but Dalvik VM is register-based. When we write code in Java, the class files contain stack based instructions and the dx tool converts the stack based instructions to register based instructions so that it can run in the Dalvik VM. So most probably there could be an algorithm somewhere which I have missed.
Also can there be an edge can where the stack could dynamically grow and shrink(which would be decided in runtime) , in that case it would be impossible to convert stack based instructions to register based. However one tool does it.
Can someone point me to the correct direction. Or know any algorithm which can help in this.

predefined preemption points among processes

I have forked many child processes and assigned priority and core to each of them. Porcess A executes at period of 3 sec and process B at a period of 6 sec. I want them to execute in such a way that the higher priority processes should preempt lower priority ones only at predefined points and tried to acheive it with semaphores. I have used this same code snippets within the 2 processes with different array values in both.
'bubblesort_desc()' sorts the array in descending order and prints it. 'bubblesort_asc()' sorts in ascending order and prints.
while(a<3)
{
printf("time in sort1.c: %d %ld\n", (int)request.tv_sec, (long int)request.tv_nsec);
int array[SIZE] = {5, 1, 6 ,7 ,9};
semaphore_wait(global_sem);
bubblesort_desc(array, SIZE);
semaphore_post(global_sem);
semaphore_wait(global_sem);
bubblesort_asc(array, SIZE);
semaphore_post(global_sem);
semaphore_wait(global_sem);
a++;
request.tv_sec = request.tv_sec + 6;
request.tv_nsec = request.tv_nsec; //if i add 1ms here like an offset to the lower priority one, it works.
semaphore_post(global_sem);
semaphore_close(global_sem); //close the semaphore file
//sleep for the rest of the time after the process finishes execution until the period of 6
clk = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &request, NULL);
if (clk != 0 && clk != EINTR)
printf("ERROR: clock_nanosleep\n");
}
I get the output like this whenever two processes get activated at the same time. For example at time units of 6, 12,..
time in sort1.c: 10207 316296689
time now in sort.c: 10207 316296689
9
99
7
100
131
200
256
6
256
200
5
131
100
99
1
1
5
6
7
9
One process is not supposed to preempt the other while one set of sorted list is printing. But it's working as if there are no semaphores. I defined semaphores as per this link: http://linux.die.net/man/3/pthread_mutexattr_init
Can anyone tell me what can be the reason for that? Is there a better alternative than semaphores?
Its printf that's causing the ambiguous output. If the results are printed without '\n' then we get a more accurate result. But its always better to avoid printf statements for real time applications. I used trace-cmd and kernelshark to visualize the behaviour of the processes.

Why my rules of bison don't work

Every time I run my parser, it will appear "syntax error in line 1 near <>" (Because there is a subroutine yyerror(char *s)). I think that's because there is something wrong with my rules in bison.
The file (c17.isc) I want to parse.
*c17 iscas example (to test conversion program only)
*---------------------------------------------------
*
*
* total number of lines in the netlist .............. 17
* simplistically reduced equivalent fault set size = 22
* lines from primary input gates ....... 5
* lines from primary output gates ....... 2
* lines from interior gate outputs ...... 4
* lines from ** 3 ** fanout stems ... 6
*
* avg_fanin = 2.00, max_fanin = 2
* avg_fanout = 2.00, max_fanout = 2
*
*
*
*
*
1 1gat inpt 1 0 >sa1
2 2gat inpt 1 0 >sa1
3 3gat inpt 2 0 >sa0 >sa1
8 8fan from 3gat >sa1
9 9fan from 3gat >sa1
6 6gat inpt 1 0 >sa1
7 7gat inpt 1 0 >sa1
10 10gat nand 1 2 >sa1
1 8
11 11gat nand 2 2 >sa0 >sa1
9 6
14 14fan from 11gat >sa1
15 15fan from 11gat >sa1
16 16gat nand 2 2 >sa0 >sa1
2 14
20 20fan from 16gat >sa1
21 21fan from 16gat >sa1
19 19gat nand 1 2 >sa1
15 7
22 22gat nand 0 2 >sa0 >sa1
10 20
23 23gat nand 0 2 >sa0 >sa1
21 19
My flex file is as follows and it is right. You can find some information about how my scanner work here.
Error in the output of my flex file
declare.h
# include <stdio.h>
# include <string.h>
# include <stdlib.h>
# define INPT 1
# define NOR 2
# define NAND 3
# define NOT 4
# define XOR 5
# define AND 6
# define BUFF 7
# define FROM 8
flex file is
%{
# include "declare.h"
# include "parse.tab.h"
/*gi=1,it's input;gi=8,it's fanout;otherwise,it's gate*/
static int gi=-1;
static int inum=0;
struct{
char *symbol;
int val;
} symtab[]={
{"inpt", INPT},
{"nor", NOR},
{"nand", NAND},
{"not", NOT},
{"xor", XOR},
{"and", AND},
{"buff", BUFF},
{"from",FROM},
{"0",0}
};
extern FILE *yyin;
extern int yylval;
%}
%start A B C D E
DIGITS [0-9]+
BLANK [ \t\n\r\f\v\b]+
ALPHA [a-z]+
%%
"*".*\n {BEGIN A; return(COMMENT);}
<A>{DIGITS} {yylval=atoi(yytext); BEGIN B; return(NUM);}
<B>{DIGITS}{ALPHA} {yylval=atoi(yytext); BEGIN C; return(GNAME);}
<C>{DIGITS} {yylval=atoi(yytext); BEGIN D; return(OPNUM);}
<C>{DIGITS}{ALPHA} {yylval=atoi(yytext); BEGIN A; return(FR);}
<D>{DIGITS} {inum=atoi(yytext);
yylval=inum;
if(gi==1)
{BEGIN A;}
if(gi!=1)
{BEGIN E;}
return(IPNUM);
}
<E>{DIGITS} {inum--;
yylval=atoi(yytext);
if(inum<0)
{BEGIN B; return(NUM);}
else
{BEGIN E; return(ILIST);}
}
{ALPHA} {yylval=lookup(yytext);
return(GTYPE);
}
">sa"[0-1] {yylval=atoi(&yytext[yyleng-1]);return(FAULT);}
{BLANK} ;
. ;
%%
int lookup(const char *s)
{
int i;
for (i = 0; symtab[i].val != 0; i++)
{
if (strcmp(symtab[i].symbol, s) == 0)
break;
}
return(symtab[i].val);
}
The right rules in bison file are as follows
parto:
| parto COMMENT
| parto parti
;
parti: NUM
{...}
GNAME
{...}
GTYPE
{...}
| parti partii
| parti partiii
;
partii:OPNUM
{...}
IPNUM
{...}
partiv
partv
;
partiii: FR
{...}
partiv
;
partiv:
| partiv FAULT
{...}
;
partv:
| partv ILIST
{...}
;
Transferring the key comments into an answer.
The first edition of the code had a couple of problems. In the scanner code, there were lines like this:
<A>{DIGITS} { yylval=atoi(yytext); return(NUM); BEGIN B; }
You should be getting warnings about unreachable code from the BEGIN operations appearing after return. The BEGIN operations have to be executed. They aren't being executed, so you're not switching into your start states.
Michael commented:
There is no warning. I've modified it as you say and edit my codes in the question. Now I put return after BEGIN. Still, "syntax error in line 1 near <�>".
This probably means you aren't compiling the C code with enough warnings. Assuming you're using GCC, add -Wall to the compilation options for starters. There's a chance the warning requires optimization too.
Have you printed the tokens as they're returned (in the Flex scanner)? Have you compiled the Bison grammar with -DYYDEBUG? You also need to turn the debug on: yydebug = 1; in the main() program. You're probably not getting the tokens you expect when you expect them. I've not tried compiling this code yet. Tracking the tokens is key (in my experience) to getting grammars to work. Otherwise, you're running blind.
The other problem (closely related) is that you need to generate the symbolic names for FAULT etc from the grammar (bison -d grammar.y generates grammar.tab.h). You'll find that COMMENT is assigned the value 258, for example. Your scanner, though, is returning other numbers altogether because they're in declare.h. You'll have to fix this mismatch. One option is to #include "grammar.tab.h" in your scanner; this is more or less normal.
In retrospect, I think this is probably the most important observation; things seemed to revert to normal C debugging after this was resolved.
(People often include 'grammar.h' and only update 'grammar.h' if the content of 'grammar.tab.h' changes, so you don't recompile the scanner all the time).
The significance of this is that the set of tokens used by a grammar tends to be fairly stable while the actions associated with the rules change all the time as the implementation of the grammar evolves. So, if it takes enough time to be worth worrying about, you can create file grammar.h that is a copy of grammar.tab.h, but only update grammar.h when the content of grammar.tab.h changes.
cmp -s grammar.tab.h grammar.h || cp grammar.tab.h grammar.h
You'd include this in the makefile rule that converts that grammar into a C file (or an object file).
If the scanner is small enough and your machine fast enough, it may be simpler not to bother with this refinement; it mattered more in the days of 50 MHz machines with a few MiB of RAM than it does in these days of multiple cores running at 2+ GHz with a few GiB of RAM.