| Problem 1Count the number of semi-colons in the input file(s). 
#include "c_api.h"
void
cobra_main(void)  // called by the front-end after preprocessing is complete
{	int cnt = 0;
	for (cur = prim; cur; cobra_nxt())  // the main loop over all tokens
	{	if (strcmp(cur->txt, ";") == 0)
		{	cnt++;
		}
	}
	printf("Number of semi-colons: %d\n", cnt);
}
To compile, link, and run this code, first cd to the $COBRA/src_app directory
and place this file there. Name it Part5_1.c and execute:$ make clean $ make c.ar # if necessary: cd ../src; make clean; cd ../src_app; make c.ar $ cc -O2 -Wall -I. -pedantic -Werror -Wshadow -std=c99 -o p5_1 Part5_1.c c.ar $ ./p5_1 *.c Number of semi-colons: 2284 Problem 2Making the code multi-threaded, using the support routines in cwe_util.c. 
#include "c_api.h"
#define mycur_nxt()	(mycur = mycur?mycur->nxt:NULL)
extern TokRange **tokrange;
extern int run_threads(void *(*f)(void*));	// from cwe_util.c
extern void set_multi(void);			// from cwe_util.c
static int *cnt;
static void
part5_init(void)
{
	cnt = (int *) emalloc(Ncore * sizeof(int));
	set_multi();
}
	
static void
part5_range(Prim *from, Prim *upto, int cid)
{	Prim *mycur;
	int local_cnt = 0;
	mycur = from;
	while (mycur_nxt() && mycur->seq <= upto->seq)
	{	if (strcmp(mycur->txt, ";") == 0)
		{	local_cnt++; // leave access to shared global to the end
	}	}
	cnt[cid] = local_cnt;
}
static void *
part5_run(void *arg)
{	int *i = (int *) arg;
	Prim *from, *upto;
	from = tokrange[*i]->from;
	upto = tokrange[*i]->upto;
	part5_range(from, upto, *i);
	return NULL;
}
static void
part5_report(void)
{	int i, total = 0;
	for (i = 0; i < Ncore; i++)
	{	total += cnt[i];
		printf("Core %d total: %d\n", i, cnt[i]);
	}
	printf("Total number of semi-colons: %d\n", total);
}
void
cobra_main(void)  // called by the front-end after preprocessing is complete
{
	part5_init();
	run_threads(part5_run);
	part5_report();
}
To compile, link, and run this code cd to the $COBRA/src_app directory
and place this file there. Name it Part5_2.c and execute:$ make clean $ make c.ar # if necessary: cd ../src; make clean; cd ../src_app; make c.ar $ cc -O2 -Wall -I. -pedantic -Werror -Wshadow -std=c99 -o p5_2 Answers_Exercises_Part5_2.c cwe_util.c c.ar -pthread $ ./p5_2 -N8 *.c Core 0 total: 280 Core 1 total: 294 Core 2 total: 310 Core 3 total: 259 Core 4 total: 279 Core 5 total: 291 Core 6 total: 306 Core 7 total: 290 Total number of semi-colons: 2309 |