threads ( c language ) in Ubunt
-
Well thanks but I've already did my homeworks, you could do it as well. From http://www.codeproject.com/Messages/2922875/HOW-TO-ASK-A-QUESTION.aspx[^]:
2. Be specific! Don't ask "can someone send me the code to create an application that does 'X'. Pinpoint exactly what it is you need help with.
...
11. If you have a school or university assignment, assume that your teacher or lecturer is also reading these forums. -
Well thanks but I've already did my homeworks, you could do it as well. From http://www.codeproject.com/Messages/2922875/HOW-TO-ASK-A-QUESTION.aspx[^]:
2. Be specific! Don't ask "can someone send me the code to create an application that does 'X'. Pinpoint exactly what it is you need help with.
...
11. If you have a school or university assignment, assume that your teacher or lecturer is also reading these forums. -
"POSIX Threads Programming"[^].
THESE PEOPLE REALLY BOTHER ME!! How can they know what you should do without knowing what you want done?!?! -- C++ FQA Lite
-
"POSIX Threads Programming"[^].
THESE PEOPLE REALLY BOTHER ME!! How can they know what you should do without knowing what you want done?!?! -- C++ FQA Lite
#include
<stdio.h>
#include
<stdlib.h>// The array that holds the data
int array[1000]
;void testSum()
{
int sum=0;int j;
for(j=0
; j< 1000 ; j++){
sum+=array[j];} printf("Testing without threads, Sum is : %d \\n",sum);
}
// This function reads a file with 1000 integers,
an integer is stored in
// each line.The function stores the integers in the arrayvoid readfile(char* file_name)
{
char ch;
FILE *fp;
fp = fopen(file_name,"r"); // read mode
if( fp == NULL )
{
perror("Error while opening the file.\n");exit(EXIT\_FAILURE);
}
char line \[5\];
/* line size */
int i=0;
printf("Reading file: ");
fputs(file\_name,stdout); printf("\\n"); while ( fgets ( line, sizeof line, fp) != NULL ) /\* read a line \*/ { if (i < 1000) { array\[i\]=atoi(line); } //debug code //fputs ( line, stdout ); /\* write the line \*/ i++;
}
// debug code //printf("i is : %d \\n",i);
fclose(fp);
printf("Reading file Complete, integers stored in array.\\n\\n");
}
int main(int argc, char* argv[])
{if (argc != 2) {
fprintf(stderr,"usage: a.out <file name>\n");/\*exit(1);
*/
return -1;}
readfile(argv[1]);
//Debug code for testing only
testSum();return 0;
}
-
"POSIX Threads Programming"[^].
THESE PEOPLE REALLY BOTHER ME!! How can they know what you should do without knowing what you want done?!?! -- C++ FQA Lite
-
0. Split your array into four parts (use the pointer to determine where you're doing the split, don't make another copy of the data) 1. Create worker threads to sum each with their portion (pointer to the beginning and size). 2. Wait for all threads to finish, sum their results. If this was a program that needed to do this over and over again, I'd also create a "thread pool" that is precreated. Creating threads on the fly is actually a pretty slow process, you want to do it sparingly.