С.Creating threads - c

the task is as follows:
Write a program that takes as parameters a set of data file names (an arbitrary number) and runs all files for parallel processing (using threads). As a processing, use the sorting method (quickSort).
I ran this program through vmbox on the QNX operating system.It has compiled but does nothing.I have a text file with numbers in my project folder and nothing happens to them.or there should be several of them..(i mean files)And one more thing. I get one warning when compiling. After this sign }, which "closes" the void *FileToArray The warning is as follows: control reaches end of non-void function.How to fix it?
I did it on the basis of methodological guidelines.But maybe I missed something. And I would be grateful if you could tell me what I'm doing wrong.
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <sys/syspage.h>
void quickSort (int *b,int left, int right){
int sort;
int Dleft = left;
int Dright = right;
sort = b[left];
printf ("%d",pthread_self());
while(left<right){
while((b[right]>=sort)&&(left<right))
right--;
if (left!=right){
b[left]=b[right];
left++;
}
while((b[left]<=sort)&&(left<right))
left++;
if(left!=right)
{
b[right]=b[left];
right --;
}
}
b[left]=sort;
sort=left;
left=Dleft;
right=Dright;
if(left<sort)
quickSort(b,left,sort-1);
if(right>sort)
quickSort(b,sort+1,right);
}
void *FileToArray(void *name){
int i =0,j =0;
int *a=(int*)malloc(sizeof(int)*2);
FILE *f=fopen(name,"r");
printf("start - %p\n",name);
while (feof(f)==0){
fscanf(f, "%d",&a[i]);
i++;
a=(int*)realloc(a,sizeof(int)*i+1);
}
fclose(f);
quickSort(a,0,i-2);
f=fopen(name,"w");
for (j=0;j<i-1;j++){
fprintf(f, "%d\n",a[j]);
}
free(a);
fclose(f);
printf("finish - %p\n",name);
}
int num_lines_per_cpu;
int num_cpus;
int main(int argc, char** argv) {
int j;
pthread_t *thread_ids;
num_cpus = syspage_ptr->num_cpu;
thread_ids=malloc(sizeof(pthread_t)*num_cpus);
num_lines_per_cpu=argc%num_cpus;
for(j=1;j<argc;j++){
pthread_create (&thread_ids[j-1],NULL,FileToArray,argv[j]);
}
for(j=0;j<argc-1;j++){
pthread_join(thread_ids[j],NULL);
}
return EXIT_SUCCESS;
}

The warning is as follows: control reaches end of non-void
function.How to fix it?
And it is exactly as it says, you're returning nothing from your function but the return type is void*.
Nowhere in that function you're returning a pointer, unless I missed it.

Related

How to use recursion in quicksort algorithm in c?

This is my first time posting so bear with me! I have to make a quicksort algorithm as an assignment for university, using c. However, when I try running the program a pop-up window opens up and informs me that the exe has stopped working. So then I started debugging and I found that the problem appears when the program enters the recursion process, as I receive around those lines a SIGSEGV type error. Unfortunately I cant find the problem so that's why I'm posting here my code, hoping that you can help me. Any further advice about my code in general will be appreciated. Thanks!
#include <stdio.h>
#include <string.h>
#define SIZE 20
void quicksort(int *first, int *last);
main()
{
FILE *fp;
int *ptr, arr[SIZE], k;
ptr=arr;
fp=fopen("numbers.txt", "r");
printf("Initial array before sorting:\n");
for (k=0; k<SIZE; k++)
{
fscanf(fp, "%d", ptr);
printf("Element[%d]:\t%d\n", k+1, *ptr);
ptr++;
}
fclose(fp);
printf("Final array after sorting:\n");
quicksort(arr, arr+SIZE-1);
for (k=0; k<SIZE; k++)
{
printf("Element[%d]:\t%d\n", k+1, *(arr+k));
}
}
void quicksort(int *first, int *last)
{
int *item_left, *item_right, *i, *j, *pivot, temp, check_left=0, check_right=0, limiter=0;
pivot=last;
while (!check_left && !check_right && limiter<10)
{
for (i=first; i<last; i++)
{
if (*i>*pivot)
{
item_left=i;
check_left=1;
break;
}
}
for (j=last; j>first; j--)
{
if (*j<*pivot)
{
item_right=j;
check_right=1;
break;
}
}
if (check_left==1 && check_right==1)
{
temp=*item_left;
*item_left=*item_right;
*item_right=temp;
check_left=0;
check_right=0;
}
limiter++;
}
temp=*item_right;
*item_right=*pivot;
*pivot=temp;
if (last-first>1)//-------problem
{
quicksort(first, item_left-1);
quicksort(item_left, last);
}//----------problem
}
So I checked the code again and I found the problem. You see, I declared some local variables in the function I was calling. This was causing trouble in the computer's memory, as every time the function was called again, it was told to create the same variables which were already created and stored in the memory. So what I did is to make all those variables needed global. This way they are created only one time.

c does not follow the program operation procedure

summary : system("clear"); isn't working well.
I'm using gcc, ubuntu 18.04 LTS version for c programming.
what I intended was "read each words and print from two text files. After finish read file, delay 3 seconds and erase terminal"
so I was make two text files, and using system("clear"); to erase terminal.
here is whole code.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
void printFiles(char *file1,char *file2,char *change1, char *change2){
FILE *f;
char *text = malloc(sizeof(char)*100);
f=fopen(file1,"r");
system("clear");
//while(!feof(f)){
while(EOF!=fscanf(f,"%s",text)){
//fscanf(f,"%s", text);
printf("%s ",text);
//usleep(20000);
}
//sleep(3);
fclose(f);
printf("\n");
//all comment problems are appear here. and if I give delay, such as usleep() or sleep, delay also appear here. Not appear each wrote part.
f=fopen(file2,"r");
//while(!feof(f)){
while(EOF!=fscanf(f,"%s",text)){
if(strcmp(text,"**,")==0){
strcpy(text,change1);
strcat(text,",");
}
else if(strcmp(text,"**")==0){
strcpy(text,change1);
}
else if(strcmp(text,"##.")==0){
strcpy(text,change2);
strcat(text,".");
}
else if(strcmp(text,"##,")==0){
strcpy(text,change2);
strcat(text,",");
}
printf("%s ",text);
//usleep(200000);
}
fclose(f);
free(text);
sleep(3); //here is problem. This part works in the above commented part "//all comment problems are appear here."
system("clear"); //here is problem. This part works in the above commented part "//all comment problems are appear here."
}
int main(){
char file1[100] = "./file1.txt";
char file2[100] = "./file2.txt";
char change1[100]="text1";
char change2[100]="text2";
printFiles(file1,file2,change1,change2);
return 0;
}
I'm very sorry, files and variables names are changed because of policy. Also, file contents also can not upload.
I can't find which part makes break Procedure-oriented programming. I think that was compiler error, because using one file read and system(clear); works well.
I also make two point variables, such as 'FILE *f1; FILE *f2; f1=fopen(file1); f2=fopen(file2)...`, but same result occur.
Is it compiler error? If it is, what should I do for fix these problem? Thanks.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
void printFiles(char *file1,char *file2,char *change1, char *change2){
FILE *f;
char *text = malloc(sizeof(char)*100);
f=fopen(file1,"r");
system("clear");
//while(!feof(f)){
while(EOF!=fscanf(f,"%s",text)){
//fscanf(f,"%s", text);
printf("%s ",text);
fflush(stdout);
//usleep(20000);
}
//sleep(3);
fclose(f);
printf("\n");
//all comment problems are appear here. and if I give delay, such as usleep() or sleep, delay also appear here. Not appear each wrote part.
f=fopen(file2,"r");
//while(!feof(f)){
while(EOF!=fscanf(f,"%s",text)){
if(strcmp(text,"**,")==0){
strcpy(text,change1);
strcat(text,",");
}
else if(strcmp(text,"**")==0){
strcpy(text,change1);
}
else if(strcmp(text,"##.")==0){
strcpy(text,change2);
strcat(text,".");
}
else if(strcmp(text,"##,")==0){
strcpy(text,change2);
strcat(text,",");
}
printf("%s ",text);
fflush(stdout);// The answer.
//usleep(200000);
}
fclose(f);
free(text);
sleep(3); //here is problem. This part works in the above commented part "//all comment problems are appear here."
system("clear"); //here is problem. This part works in the above commented part "//all comment problems are appear here."
}
int main(){
char file1[100] = "./file1.txt";
char file2[100] = "./file2.txt";
char change1[100]="text1";
char change2[100]="text2";
printFiles(file1,file2,change1,change2);
return 0;
}
Hint for
That's probably just buffering. Do fflush(stdout); before you sleep. – melpomene
Thanks.
You can try this solution for delay.
#include <time.h>
#include <stdio.h>
void delay(double seconds)
{
const time_t start = time(NULL);
time_t current;
do
{
time(&current);
} while(difftime(current, start) < seconds);
}
int main(void)
{
printf("Just waiting...\n");
delay(3);
printf("...oh man, waiting for so long...\n");
return 0;
}
Following solution is pretty quite the same of previous one but with a clear terminal solution.
#include <time.h>
#include <stdio.h>
#ifdef _WIN32
#define CLEAR_SCREEN system ("cls");
#else
#define CLEAR_SCREEN puts("\x1b[H\x1b[2J");
#endif
void delay(double seconds)
{
const time_t start = time(NULL);
time_t current;
do
{
time(&current);
} while(difftime(current, start) < seconds);
}
int main(void)
{
printf("Just waiting...\n");
delay(2); //seconds
printf("...oh man, waiting for so long...\n");
delay(1);
CLEAR_SCREEN
return 0;
}

libmp3lame encoding to char array slow

I am trying to encode pcm audio that i generated using "mplayer -ao pcm:nowaveheader" into mp3 with a c program. I don't want to write the mp3 to a file, I want to keep in in an array until i need to write it to a file, I wrote this, and it appears to work in a short .9 second test file, but it is very slow. What exactly is wrong?
#include <stdio.h>
#include <stdlib.h>
#include <lame/lame.h>
lame_global_flags *gfp;
int loopcount;
int inputSize;
FILE *fp=NULL;
FILE *fpo=NULL;
char *mp3buffer;
int mp3buffersize;
int countsize;
int x=0;
int y=0;
short *pcmbuffer;
short *lpcmbuffer;
short *rpcmbuffer;
int parse()
{
printf("loading PCM data...\n");
pcmbuffer=malloc(inputSize);
fread(pcmbuffer,2,(inputSize/2),fp);
printf("data in buffer\n");
printf("splitting left and right channels\n");
lpcmbuffer=malloc(inputSize/2);
countsize=((inputSize/4)-1);
while (x<=countsize)
{
lpcmbuffer[x]=pcmbuffer[x*2];
x++;
}
x=0;
rpcmbuffer=malloc(inputSize/2);
while (x<=countsize)
{
rpcmbuffer[x]=pcmbuffer[(x*2)+1];
x++;
}
x=0;
printf("starting lame\n");
gfp=lame_init();
lame_set_num_channels(gfp,2);
lame_set_in_samplerate(gfp,44100);
lame_set_brate(gfp,256);
lame_set_mode(gfp,1);
lame_set_quality(gfp,5);
if (lame_init_params(gfp)<0)
{
return 1;
}
}
encode()
{
x=0;
mp3buffersize=(1.25*countsize+7200);
mp3buffer=malloc(mp3buffersize);
while (x!=countsize)
{
lame_encode_buffer(gfp,lpcmbuffer,rpcmbuffer,x,mp3buffer,mp3buffersize);
x++;
y++;
if(y==1000)
{
printf("%d %d\n",countsize,x);
y=0;
}
}
x=0;
lame_encode_flush(gfp,mp3buffer,mp3buffersize);
fpo=fopen("test.mp3","w");
fwrite(mp3buffer,1,countsize,fpo);
}
decode()
{
}
bounty()
{
//the quicker picker upper
printf("closing files\n");
fclose(fpo);
fclose(fp);
printf("closing lame\n");
lame_close(gfp);
printf("freeing pcmbuffer\n");
free(pcmbuffer);
free(lpcmbuffer);
free(rpcmbuffer);
free(mp3buffer);
}
int main(int argc,char **argv)
{
loopcount=atoi(argv[1]);
fp=fopen(argv[2],"r");
if (fp==NULL)
{
printf("File Read Error\n");
return 0;
}
fseek(fp,0,SEEK_END);
inputSize=ftell(fp);
fseek(fp,0,SEEK_SET);
printf("detected a %d byte(s) file\n",inputSize);
printf("Proceeding with parsing and importing...\n");
if (parse()==1)
{
printf("lame init error\n");
}
printf("loopcount is %d\n",loopcount);
encode();
//the Quicker Picker Upper
bounty();
return 0;
}
Short answer, make this your encode function:
void encode()
{
mp3buffersize=(1.25*countsize+7200);
mp3buffer=malloc(mp3buffersize);
lame_encode_buffer(gfp, lpcmbuffer, rpcmbuffer, countsize, mp3buffer, mp3buffersize);
lame_encode_flush(gfp,mp3buffer,mp3buffersize);
fpo=fopen("test.mp3","w");
fwrite(mp3buffer,1,countsize,fpo);
}
I've never used lame, but, it looked like in your encode() function you were calling lame_encode_buffer() again and again, overwriting the result each time, and doing from 0 to countsize as the number of samples per channel (argument 4).
Other comments:
Why aren't you using lame_encode_buffer_interleaved()? Much of your parse() function is just undoing the existing interleaving of your file, seems like a waste.
IMO, the mass of global variables you're using are UGLY. Ideally your encode() would look more like: encode(lame_global_flags *gfp, const short * lpcmbuffer, const short * rpcmbuffer, const int countsize) this way it is clear from reading the parameter list the type of the variables, and that they must have come from/been set by the caller. const is nice to clarify that they're only for reading.
Finally, you really should have done some profiling, e.g. printing time differences between entry and exit of functions, to figure where your time sink was, and posted what you'd found. I ventured a guess looking at your loops, the encode() function had the only loop with any meat in it. I never ran your program, maybe I'm 100% wrong.

C compile error: Id returned 1 exit status

For some reason, when I try compiling a program, the compiler says permission denied and Id returned 1 exit status. Could anyone tell me what that means? Thank you
#include <stdio.h> /* Library inclusions */
#include "genlib.h"
#include "simpio.h"
int binSearch(int val, int numbers[], int size1); /* prototypes */
void sortArray (int numbers[], int size1);
int indexMax (int numbers[], int low, int high);
void swap (int numbers[], int loc, int loc1);
void getArray (int numbers[], int size1);
void displayArray (int numbers[], int size1);
main()
{
int value, size1;
printf("Enter the number of elements: ");
size1=GetInteger();
int numbers[size1];
getArray(numbers, size1);
sortArray(numbers, size1);
displayArray(numbers, size1);
printf("\nEnter value to find: ");
value=GetInteger();
binSearch(value, numbers, size1);
getchar();
}
void sortArray (int numbers[], int size1) /*Function sortArray*/
{
int i , maxInd;
for (i= size1-1; i>=0;i--)
{
maxInd=indexMax(numbers, 0, i);
swap (numbers, i, maxInd);
}
}
void displayArray (int numbers[], int size1) /*Function displayArray*/
{
int i;
printf("This is the sorted set of numbers: \n");
for (i=0; i< size1; i++)
{
printf ("%d\t", numbers[i]);
}
}
void getArray (int numbers[], int size1) /*Function getArray*/
{
int i;
for (i=0; i<size1; i++)
{
printf ("Enter the values of the %d elements: ", size1);
numbers[i]=GetInteger();
}
}
int indexMax (int numbers[], int low, int high) /*Function indexMax*/
{
int i, maxInd;
maxInd=high;
for (i=low;i<=high;i++)
{
if (numbers[i]>numbers[maxInd])
{
maxInd =i;
}
}
return (maxInd);
}
void swap (int numbers[], int loc, int loc1) /*Function swap*/
{
int temp;
temp=numbers[loc];
numbers[loc]=numbers[loc1];
numbers[loc1]=temp;
}
int binSearch(int val, int numbers[], int size1) /*Function binSearch*/
{
int low, high, mid;
low=0;
high=size1-1;
while(low<=high)
{
mid=(low+high)/2;
if(val<numbers[mid])
{
high=mid-1;
}
else if(val>numbers[mid])
{
low=mid+1;
}
else if(val==numbers[mid])
{
printf("Your number is in location %d\n", mid+1);break;
}
else
{
printf("Your value is not in the array.");
}
}
}
The above is the binary search algorithm code I tried to compile.
I may guess, the old instance of your program is still running. Windows does not allow to change the files which are currently "in use" and your linker cannot write the new .exe on the top of the running one. Try stopping/killing your program.
I bet for sure, that this is because you didn't close the running instance of the program before trying to re-compile it.
Generally, ld.exe returns 1 when it can't access required files. This usually includes
Can't find the object file to be linked (or Access denied)
Can't find one or more symbols to link
Can't open the executable for writing (or AD)
The program looks completely fine, so the second point should not hit. In usual cases, it's impossible for ld to fail to open the object file (unless you have a faulty drive and a dirty filesystem), so the first point is also nearly impossible.
Now we get to the third point. Note that Windows not allow writing to a file when it's in use, so the running instance of your program prevents ld.exe from writing the new linked program to it.
So next time be sure to close running programs before compiling.
Using code::blocks , I have solved this error by doing :
workspace properties > build target > build target files
and checking every project file.
You may compiling your program while another program may be running in background.
Firstly, see if another program is running .Close it and then try ro compile.
Just try " gcc filename.c -lm" while compiling the program ...it worked for me
1d returned 1 exit status error
First of all you have to create a project by clicking file new and then project and give project name select the language c or c++ and select empty also.
Then your program is under that project... And then give a program name save it.... Ensure that your under some project to compile and run a program...
Is a simple MAYUS word. verify the log.
it could be that you just said main{....I use int main{ when I start my main.
This answer is written for C++ developers, because I was haunted by such problem as one. Here is the solution:
Instead of
main()
{
}
please type
int main()
{
}
so the main function can be executed.
By the way,
if you compile a C/C++ source file with no main function to execute,
there will definitely be a bug message saying:
"[Error] Id returned 1 exist status"
But sometimes we just don't need main function in the file,
in such a case, just ignore the bug message.
My solution is to try to open another file that you can successfully run that you do at another PC, open that file and run it, after that copy that file and make a new file. Try to run it.
it seems as if it comes when u have an previous compiled version of your program running

Coredump in selfmade arrayList

i'm current working on a homework assesment where i'm programming a program ment to stitch textfiles with a piece of an ascii image to create a complete image of all the pieces. The way i intended to write the code is having a while loop looking through a directory finding the parts and adding them to an array. However in my AddFile method(or when i call it to be precise) i get a coredump.. I just started working with c so i dont know if it is very obvious to some of you why i get a coredump or more complicated. Also, i originaly wrote the addFile method to use and accept int's instead of the FILE type, at that point it worked perfectly without any coredumps so i suspect (but hey i might be wrong) that it went wrong when i tried to implement it with the FILE type.
#include <stdio.h>
#include <stdlib.h>
typedef struct{
int listSize;
int listCapacity;
FILE *fileStream;
}FileList;
void addFile(FileList* list, FILE file)
{
if((*list).listSize<(*list).listCapacity)
{
(*list).fileStream[(*list).listSize]=file;
(*list).listSize+=1;
}
else
{
FILE *tempArray = calloc((*list).listSize,sizeof(FILE));
for(int i=0; i<(*list).listSize; i++)
{
tempArray[i]=(*list).fileStream[i];
}
//Do something with array...
free((*list).fileStream);
(*list).listCapacity=((*list).listCapacity)*2;
(*list).fileStream=calloc((*list).listCapacity,sizeof(FILE));
for(int i=0; i<(*list).listSize; i++)
{
(*list).fileStream[i]=tempArray[i];
}
(*list).fileStream[(*list).listSize]=file;
(*list).listSize+=1;
free(tempArray);
}
}
int main()
{
FileList intList;
intList.listSize=0;
intList.listCapacity=1;
intList.fileStream=calloc(intList.listCapacity,sizeof(int));
int fileYcoord=0;
int fileXcoord=0;
while(1)
{
char fileName [100];
int fileNameLength=sprintf(fileName,"part_%02d-%02d",fileXcoord,fileYcoord);
FILE * pFile = fopen (fileName,"r");
if(pFile!=NULL)
{
printf("- ! found file: %s - name length : %d \n",fileName,fileNameLength);
addFile(&intList,*pFile);
fclose(pFile);
fileXcoord++;
}
else
{
if(fileXcoord!=0)
{
fileYcoord+=1;
fileXcoord=0;
}
else
{
break;
}
}
}
printf("size %d , %d",fileXcoord, fileYcoord);
free(intList.fileStream);
return 0;
}
The call to addFile() is dereferencing a FILE *, producing a value of type FILE. This is wrong, this is an opaque type and should always be handled by pointers.

Resources