Tilted Forum Project Discussion Community  

Go Back   Tilted Forum Project Discussion Community > Interests > Tilted Technology


 
 
LinkBack Thread Tools
Old 02-05-2005, 02:10 PM   #1 (permalink)
Dreams In Digital
 
SiNai's Avatar
 
Location: Iowa
[C] Problems with threading

So, I'm taking a course on Operating Systems, and just got a (relatively simple) project to complete. Catch is, it's in C, and I don't know C, and I have to use Unix, which I'm catching on to, at least. I know Java and Ada. The task is simple: I need to take the program supplied, and make it threaded. At least 3 threads need to be running concurrently. Anyway.. here is the code I get:

Code:
/* Programming Project #1
 * Operating Systems, Spring 2005*/
#include <pthread.h>
#include <stdio.h>
#include <math.h>

/* This program successively tests integers for prime numbers.  Return the Nth
prime number, where N is the value pointed to by *ARG. */

void * compute_prime (void * arg)
{
  int candidate = 2;
  int n = *((int*) arg); /* The parameter passed here is only an int so
                            we can abuse this feature by straight casting */

  while (1) {
    int factor;
    int is_prime = 1;
    int upper_limit = (int) sqrt((double)candidate); /*You need only test up to sqrt(x)
                                                     divisiors of x */
    /* Test primality by successive division */
    for (factor = 2; factor <= upper_limit; ++factor)
      if (candidate % factor == 0) {
        is_prime = 0; /*false*/
        break;
      }

    /* Is this the prime number that we're looking for? */
    if (is_prime) {
      if (--n == 0)
        /* Return the desired prime number as the thread return value */
        return (void*) candidate;
    }
    ++candidate;
  }


  return NULL;

}

int main () {
  pthread_t thread;
  int which_prime = 5000;
  int prime;

  /* Start the computing thread, up to the "which prime" prime number. */
  pthread_create(&thread, NULL, &compute_prime, &which_prime);

  /* Wait for the prime number thread to complete, and get the result */
  pthread_join(thread, (void*) &prime);

  /* Print the largest prime that it computed */
  printf("The %dth prime number computed is %d.\n", which_prime, prime);
  return 0;
}
So, I worked around a little bit, and here's what I got compiled:

Code:
struct ranges
{
  int begin;
  int end;
};

void * compute_prime (void * params)
{
  struct ranges* p = (struct ranges*) params;
  int candidate = p -> begin;
  int n = p -> end; /* The parameter passed here is only an int so
                          we can abuse this feature by straight casting */



  while (1)
  {
    int factor;
    int is_prime = 1;
    int upper_limit = (int) sqrt(candidate); /*You need only test up to sqrt(x)
                                                     divisiors of x */

    /* Test primality by successive division */
    for (factor = 2; factor <= upper_limit; ++factor)
    {
      if (candidate % factor == 0)
      {
        is_prime = 0; /*false*/
        break;
      }
    }

    /*At this point, we know primality*/
    /* Is this the prime number that we're looking for? */
    if (is_prime)
    {
      if (--n == 0)
        /* Return the desired prime number as the thread return value */
        return (void*) candidate;
    }
    ++candidate;
  }


  return NULL;
}

int main () {
  pthread_t thread1, thread2, thread3;
  int prime1, prime2, prime3;

  int which_prime     =    6;
  int begin           =    2;
  int final_result    =    0;
  int first_third     = which_prime/3;
  int final_third     = (first_third * 2);

  struct ranges thread1_args, thread2_args, thread3_args;
  thread1_args.begin = begin;
  thread1_args.end   = first_third - 1;
  thread2_args.begin = first_third;
  thread2_args.end   = final_third - 1;
  thread3_args.begin = final_third;
  thread3_args.end   = which_prime -1;

  /* Wait for all threads to complete, and grab the values when they are done */
  pthread_join(thread1, (void*) &prime1);
  pthread_join(thread2, (void*) &prime2);
  pthread_join(thread3, (void*) &prime3);


  /* Start 3 threads, each computes the amount of primes in one third of which_prime */
  pthread_create(&thread1, NULL, &compute_prime, &thread1_args);
  pthread_create(&thread2, NULL, &compute_prime, &thread2_args);
  pthread_create(&thread3, NULL, &compute_prime, &thread3_args);

printf("first thread %d .\n", prime1);
  printf("second thread %d .\n", prime2);
  printf("third thread %d .\n\n", prime3);
  /* Print the largest prime that it computed */
  printf("The %dth prime number computed is %d.\n", which_prime, prime3);
  return 0;

}

I get a quick Seg Fault after running my program. I know it makes it to creating the threads, but never past creating all 4 threads, so the problem lies somewhere in there. Keep in mind I know nothing about C.

My first reaction to the Seg Fault was "Well, maybe final_result is being used before all threads have returned", but, pthread_join is supposed to wait until threads have finished before going on, right?

[edit]I'm almost certain now that my threads dont work right. Thinking I should add a field to my structs.. Or perhaps that this isn't where the threads should go in the first place..




[edit2]: Updated my attempt at code. Refer to my reply down the page..
__________________
I can't seem to remember now
What it was like- to live life, before you.. symbiont

Last edited by SiNai; 02-08-2005 at 02:02 PM..
SiNai is offline  
Old 02-08-2005, 09:37 AM   #2 (permalink)
Crazy
 
Location: Salt Town, UT
Typically in threads, you don't attempt to pass values back in the pthread_join commands, what you typically do is you have them write their results into a shared structure. Otherwise you are casting things to and from a void * very often.

Other than that, it appears that a majority of your casting is incorrect, and that is what is causing your crash, it is attempting to dereference a pointer of different size.

Sorry I can't be of more help, but I just like giving hints and not complete solutions to homework.
Rawb is offline  
Old 02-08-2005, 12:05 PM   #3 (permalink)
Psycho
 
noodles's Avatar
 
Location: sc
hmm.
when i was in this kind of class, i had to do program a thread simulation from scratch :-X
(side note: the exact point of this project of yours has me slightly at a loss, unless i'm missing something)

i know nothing about pthreads.h
but here's my advice for you on this particular problem: use GDB

figure out what line its seg faulting in and see if that helps you any.
__________________
This is what is hardest: to close the open hand because one loves.
Nietzsche
noodles is offline  
Old 02-08-2005, 01:59 PM   #4 (permalink)
Dreams In Digital
 
SiNai's Avatar
 
Location: Iowa
Thanks for the replies.

What is GDB?

You're right- the casting was all wrong- I didn't want to do any casting, I just substituted some code for other code, not knowing what I was doing.. got the casting out and lo! It produced some output.

Okay. Trying to explain my situation better:

The program that is given- I need to make 3 concurrently running threads, that do not share any variables, that can complete this task. (The program computes the number of primes, given by which_prime). My first thought was to split into 3 threads. If n = 100, the first thread computes 1..33, second computes 34..66, last computes 67..100. Okay. But for the second thread to compute the 34th prime number, it needs to know the 33rd prime number, right? Of course, the first thread could return the 33rd, then let the 2nd thread go, but now that's not concurrent. Also, I could use a shared variable to let each start where the last left off, but now they're sharing variables!

Actually, here's exactly what the assignment is:
http://math-cs.cns.uni.edu/~gray/project01.pdf

How can I get around this? I'm beginning to hate this project because it seems not like a "programming project", but a "try to figure this out, and if you can't think outside the box you're screwed"..
__________________
I can't seem to remember now
What it was like- to live life, before you.. symbiont
SiNai is offline  
Old 02-08-2005, 06:03 PM   #5 (permalink)
Crazy
 
Location: Salt Town, UT
I read through the text, and I didn't see anything about not sharing variables.

But, if you really don't want to share variables, well, I would have each thread create a linked list for each prime number it finds. Add a link to the head of the list to the struct that you pass by reference into the thread functions. Then when all three (or four) threads finish, you will have three linked lists of all of the prime numbers in that area.

This however assumes that you know how to handle linked lists in C.
Rawb is offline  
Old 02-08-2005, 06:48 PM   #6 (permalink)
Dreams In Digital
 
SiNai's Avatar
 
Location: Iowa
Yeah, we aren't supposed to share variables, it's under item 3.

Actually, I have a solution. I modified the entire framework quite a bit, so that the function call only returns whether a value is prime or not, and based loops around that.

If I knew how to implement a linked list in C, it may be plausable, but this is my first time in C. Thanks for the suggestions, though.

Here is my final code- it works, not quite as elegant as it could be since I have to account for small amounts, but I found it a nice solution:

Code:
/* Programming Project #1
 * Operating Systems, Spring 2005*/
#include <pthread.h>
#include <stdio.h>
#include <math.h>

/* This program successively tests integers for prime numbers.  Return the Nth
prime number, where N is the value pointed to by *ARG. */

void * compute_prime (void * params)
{

  int candidate = * ((int*) params);

  int factor;
  int is_prime = 1;
  int upper_limit = (int) sqrt(candidate); /*You need only test up to sqrt(x)
                                                      divisiors of x */

  /* Test primality by successive division */
  for (factor = 2; factor <= upper_limit; ++factor)
  {
      if (candidate % factor == 0)
      {
        is_prime = 0; /*false*/
        break;
      }
  }
  return (int*)is_prime;
}

int main () {
  pthread_t thread1, thread2, thread3, thread4;
  int prime1, prime2, prime3, prime4;
  int isPrime1, isPrime2, isPrime3, isPrime4;

  int which_prime     =    10;
  int factor          =    3;            //Amount of concurrent threads we are using
  int loop_control1   =    1;            //Counter for first loop
  int loop_control2   =    0;            //Counter for second loop
  int finished        = which_prime - (factor +2); //want to do the last (factor) on our own, plus 1 and 2 are given
  int answer;

  //This solution breaks down for small cases: hard-coded for "sanity check"
  if (which_prime == 2)
          printf("The %dth prime is 2.\n", which_prime);
  if (which_prime == 3)
          printf("The %dth prime is 5.\n", which_prime);
  if (which_prime == 4)
          printf("The %dth prime is 7.\n", which_prime);
  if (which_prime == 5)
          printf("The %dth prime is 11.\n", which_prime);

  while(1)
  {
        //Hard coded for small case "sanity check"
        if (which_prime < 6)
                break;

        prime1 = factor * loop_control1;
        prime2 = prime1 +1;
        prime3 = prime2 +1;

        /* Start 3 threads, each returns if it's number is prime*/
        pthread_create(&thread1, NULL, &compute_prime, &prime1);
        pthread_create(&thread2, NULL, &compute_prime, &prime2);
        pthread_create(&thread3, NULL, &compute_prime, &prime3);

        /* Wait for all threads to complete, and grab the values when they are done */
        pthread_join(thread1, (void*) &isPrime1);
        pthread_join(thread2, (void*) &isPrime2);
        pthread_join(thread3, (void*) &isPrime3);
        if (isPrime1)
        {
                --finished;
                if (finished == 0)
                {
                        answer = prime1;
                        break;
                }
        }

        if (isPrime2)
        {
                --finished;
                if (finished == 0)
                {
                        answer = prime2;
                        break;
                }
        }
        if (isPrime3)
        {
                --finished;
                if (finished == 0)
                {
                        answer = prime3;
                        break;
                }
        }

        ++loop_control1;
  }

  //Exactly 3 are left: test each number after what last loop gave us,
  //but only increment for loop's counter if one is found
  loop_control2 = factor; //need to find the last (factor) primes
  while (1)
  {
          //Hard coded for small case "sanity check"
          if (which_prime < 6)
                break;

          answer = answer + 1;
          pthread_create(&thread4, NULL, &compute_prime, &answer);
          pthread_join(thread4, (void*) &isPrime4);

          if (isPrime4)
          {
                  --loop_control2;
                  if (loop_control2 == 0)
                        break;
          }
  }
  //after this, answer should be the correct prime
  /* Print the largest prime that it computed */
  //Hard coded for small case "sanity check"
  if (which_prime > 5)
        printf("The %dth prime number computed is %d.\n", which_prime, answer);
  return 0;
}
Thanks again for the replies. Got me thinkin
__________________
I can't seem to remember now
What it was like- to live life, before you.. symbiont
SiNai is offline  
Old 02-08-2005, 08:42 PM   #7 (permalink)
Psycho
 
noodles's Avatar
 
Location: sc
google or do a man on GDB. its very useful.

and i agree that this code is more of a problem solving than a coding project.
__________________
This is what is hardest: to close the open hand because one loves.
Nietzsche
noodles is offline  
Old 02-28-2005, 08:16 AM   #8 (permalink)
Junkie
 
DDD>GDB DDD has a nice front end gui on it. Use that for debugging especially if you haven't used GDB before. Although i'm not sure how well DDD/GDB work with threads.
Rekna is offline  
 

Tags
problems, threading


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On



All times are GMT -8. The time now is 07:03 PM.

Tilted Forum Project

Powered by vBulletin® Version 3.8.7
Copyright ©2000 - 2024, vBulletin Solutions, Inc.
Search Engine Optimization by vBSEO 3.6.0 PL2
© 2002-2012 Tilted Forum Project

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360