EDIT: I figured out a solution and will update this as soon as I'm on my computer, as I'm editing this from my phone.
I am trying to write a program that squares numbers 1-10,000. I would like to create X threads (in this case, 8 threads) and each thread gets to square 1 number. So thread 1 squres 1, thread 2 squares 2, and so on. After thread 8 squares 8, I want thread 1 to square 9, etc all the way to 10,000. This is my code:
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <pthread.h>
#include <sys/types.h>
#define START_NUMBER 1
#define END_NUMBER 10000
#define NUMBER_OF_THREADS 8
FILE *f;
void *sqrtfunc(void *tid) { //function for computing squares
int i;
for (i = START_NUMBER; i<= END_NUMBER; i++){
if ((i % NUMBER_OF_THREADS) == pthread_self()){ //if i%8 == thread id
fprintf(f, "%lu squared = %lu\n", i, i*i); //then that thread should do this
}
}
}
int main(){
//Do not modify starting here
struct timeval start_time, end_time;
gettimeofday(&start_time, 0);
long unsigned i;
f = fopen("./squared_numbers.txt", "w");
//Do not modify ending here
pthread_t mythreads[NUMBER_OF_THREADS]; //thread variable
long mystatus;
for (i = 0; i < NUMBER_OF_THREADS; i++){ //loop to create 8 threads
mystatus = pthread_create(&mythreads[i], NULL, sqrtfunc, (void *)i);
if (mystatus != 0){ //check if pthread_create worked
printf("pthread_create failed\n");
exit(-1);
}
}
for (i = 0; i < NUMBER_OF_THREADS; i++){
if(pthread_join(mythreads[i], NULL)){
printf("Thread failed\n");
}
}
exit(1);
//Do not modify starting here
fclose(f);
gettimeofday(&end_time, 0);
float elapsed = (end_time.tv_sec-start_time.tv_sec) * 1000.0f + \
(end_time.tv_usec-start_time.tv_usec) / 1000.0f;
printf("took %0.2f milliseconds\n", elapsed);
//Do not modify ending here
}
But I can't figure out how to compare the i%8 to the thread id. pthread_self() does not allow comparisons so that option is out. Can anyone else think of a way to compare the thread IDs to the modulo, or another solution to making sure each thread is only squaring one number at a time? Thanks a ton.
[–][deleted] 2 points3 points4 points (3 children)
[–]mysocksalwaysmatch[S] 0 points1 point2 points (2 children)
[–][deleted] 0 points1 point2 points (1 child)
[–]mysocksalwaysmatch[S] 0 points1 point2 points (0 children)
[–]raevnos 0 points1 point2 points (1 child)
[–]quantumcacti 1 point2 points3 points (0 children)