Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 654389
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T22:29:20+00:00 2026-05-13T22:29:20+00:00

The following code is a simple thread game, that switches between threads causing the

  • 0

The following code is a simple thread game, that switches between threads causing the timer to decrease.

It works fine for 3 threads, causes and Abort(core dumped) for 4 threads, and causes a seg fault for 5 or more threads.

Anyone have any idea why this might be happening?

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <errno.h>
#include <assert.h>

int volatile num_of_threads;
int volatile time_per_round;
int volatile time_left;
int volatile turn_id;
int volatile thread_running;
int volatile can_check;
void *  player (void * id_in){
 int id= (int)id_in;
 while(1){
  if(can_check){
   if (time_left<=0){
    break;
   }
   can_check=0;
   if(thread_running){
    if(turn_id==id-1){
     turn_id=random()%num_of_threads;
     time_left--;
    }
   }
   can_check=1;
  }
 }
 pthread_exit(NULL);
}
int main(int argc, char *args[]){
 int i;
 int buffer;
 pthread_t * threads =(pthread_t *)malloc(num_of_threads*sizeof(pthread_t));
 thread_running=0;
 num_of_threads=atoi(args[1]);
 can_check=0;
 time_per_round = atoi(args[2]);
 time_left=time_per_round;
 srandom(time(NULL));
 //Create Threads
 for (i=0;i<num_of_threads;i++){
  do{
  buffer=pthread_create(&threads[i],NULL,player,(void *)(i+1));
  }while(buffer == EAGAIN);
 }
 can_check=1;

 time_left=time_per_round;
 turn_id=random()%num_of_threads;
 thread_running=1;

 for (i=0;i<num_of_threads;i++){
  assert(!pthread_join(threads[i], NULL));
 }
 return 0;
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T22:29:21+00:00Added an answer on May 13, 2026 at 10:29 pm

    See below on why you should not depend on volatile in pthreads. However, your specific problem is probably because you malloc your pthread array, based on the num_of_threads variable before you’ve actually set num_of_thread from argv[]:

    pthread_t *threads = (pthread_t *)malloc (num_of_threads * sizeof (pthread_t));
    thread_running = 0;
    num_of_threads = atoi (args[1]);
    

    So there’s a very good chance you’re writing beyond the end of the threads array. The num_of_threads variable will probably be zero on start-up which means you’re not allocating what you think you are. Move the allocation to after the extraction of the arguments and that should fix it.


    And now, for your viewing pleasure :-), my original rant on the unsafe use of volatile, which I still stand by.

    Do not rely on volatile to protect your shared variables. The correct way to do this is with the pthread_mutex_blab_blah_blah calls.

    Of particular note, examine this code segment:

    if (can_check) {
       if (time_left <= 0) {
        break;
       }
       // URK!!
       can_check=0;
    

    URK!! is the point where your current thread may be switched out and another run, leading to the possibility that two threads can be running a critical section of code.

    My advice is to forget the can_check altogether and just protect all the shared variables with a mutex, something like (from memory):

    void *player (void * id_in) {
        int id = (int)id_in;
        while (1) {
            pthread_mutex_lock (&mutex);
            if (time_left <= 0) {
                pthread_mutex_unlock (&mutex);
                break;
            }
            if (thread_running) {
                if (turn_id == id-1) {
                    turn_id = random() % num_of_threads;
                    time_left--;
                }
            }
            pthread_mutex_unlock (&mutex);
        }
        pthread_exit(NULL);
    }
    

    Then put at file-level:

    pthread_mutexattr_t mutexattr;  // prob. not needed at file level.
    pthread_mutex_t mutex;
    

    and, in main, before starting any other threads:

    pthread_mutexattr_init (&mutexattr);
    // Change attributes if needed.
    pthread_mutex_init (&mutex, &mutex_attr);
    
    // Then run all you other stuff here, make sure you've joined with all threads.
    
    pthread_mutex_destroy (&mutex);
    

    Oh yeah, although I haven’t done it, you should also check the return codes for all those mutex calls. I’m not going to add that since it’ll clog up the answer with unnecessary detail, but it’s good practice.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 374k
  • Answers 374k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer W3C Validation isn't everything. It's not the end of the… May 14, 2026 at 7:56 pm
  • Editorial Team
    Editorial Team added an answer Make sure you inherit from gwt-openlayers by adding the following… May 14, 2026 at 7:56 pm
  • Editorial Team
    Editorial Team added an answer Go to your Toolbox, right click anywhere inside and select… May 14, 2026 at 7:56 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.