tid manager releasing tid in batches grouped by same sleep time in C

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#define MIN_TID 300
#define MAX_TID 5000
#define NUM_TIDS (MAX_TID - MIN_TID + 1)

unsigned char *bitset; // Global variable to hold the bitset
pthread_mutex_t tid_mutex = PTHREAD_MUTEX_INITIALIZER;

struct ThreadArgs {
  int min_sleep;
  int max_sleep;
};

// Function to check if a bit is set (1)
int isBitSet(const unsigned char *bitset, int tid) {
  int byte_index = (tid - MIN_TID) / 8;
  int bit_index = (tid - MIN_TID) % 8;
  return (bitset[byte_index] & (1 << bit_index)) != 0;
}

// Function to allocate the bitset data structure (b)
int allocate_map() {
  bitset = (unsigned char *)malloc((NUM_TIDS + 7) / 8);
  if (bitset == NULL) {
    return -1; // Allocation failed
  }
  memset(bitset, 0, (NUM_TIDS + 7) / 8); // Initialize all bits to 0 (available)
  return 1;                              // Success
}

// Function to allocate a unique TID (c)
int allocate_tid() {
  int tid = -1;
  pthread_mutex_lock(&tid_mutex);
  for (int i = MIN_TID; i <= MAX_TID; i++) {
    if (!isBitSet(bitset, i)) {
      tid = i;
      int byte_index = (tid - MIN_TID) / 8;
      int bit_index = (tid - MIN_TID) % 8;
      bitset[byte_index] |= (1 << bit_index);
      break;
    }
  }
  pthread_mutex_unlock(&tid_mutex);
  return tid;
}

// Function to relinquish a TID (d)
void release_tid(int tid) {
  pthread_mutex_lock(&tid_mutex);
  if (tid >= MIN_TID && tid <= MAX_TID) {
    int byte_index = (tid - MIN_TID) / 8;
    int bit_index = (tid - MIN_TID) % 8;
    bitset[byte_index] &= ~(1 << bit_index);
  }
  pthread_mutex_unlock(&tid_mutex);
}

void *thread_function(void *arg);

int main(int argc, char *argv[]) {
  // Simulate command line arguments for testing
  char *test_argv[] = {"program_name", "-n", "50", "-l", "2", "-h", "5"};
  argc = 7;
  argv = test_argv;

  int num_threads = 100; // Default number of threads
  int min_sleep = 1;     // Default minimum sleep time
  int max_sleep = 10;    // Default maximum sleep time

  struct ThreadArgs thread_args;
  thread_args.min_sleep = min_sleep;
  thread_args.max_sleep = max_sleep;

  // Parse command-line arguments
  for (int i = 1; i < argc; i++) {
    switch (argv[i][1]) {
    case 'n':
      num_threads = atoi(argv[++i]);
      break;
    case 'l':
      min_sleep = atoi(argv[++i]);
      break;
    case 'h':
      max_sleep = atoi(argv[++i]);
      break;
    default:
      printf("Invalid argument: %sn", argv[i]);
      return 1;
    }
  }

  thread_args.min_sleep = min_sleep;
  thread_args.max_sleep = max_sleep;

  // Initialize the TID manager
  if (allocate_map() == -1) {
    printf("Failed to initialize TID managern");
    return 1;
  }

  // Seed the random number generator
  srand(time(NULL));

  // Create threads
  pthread_t threads[num_threads];
  for (int i = 0; i < num_threads; i++) {
    if (pthread_create(&threads[i], NULL, thread_function, &thread_args) != 0) {
      fprintf(stderr, "Error creating thread %dn", i);
      return 1;
    }
  }

  // Wait for threads to finish
  for (int i = 0; i < num_threads; i++) {
    if (pthread_join(threads[i], NULL) != 0) {
      fprintf(stderr, "Error joining thread %dn", i);
      return 1;
    }
  }

  printf("All threads finishedn");

  // Free the bitset memory
  free(bitset);

  // Destroy the mutex
  pthread_mutex_destroy(&tid_mutex);

  return 0;
}

void *thread_function(void *arg) {
  struct ThreadArgs *args = (struct ThreadArgs *)arg;
  int min_sleep = args->min_sleep;
  int max_sleep = args->max_sleep;

  // Seed the random number generator with a combination of time and thread ID
  unsigned int seed = time(NULL) ^ pthread_self();
  srand(seed);

  // Allocate a TID
  int tid;
  while (1) {
    tid = allocate_tid();
    pthread_mutex_unlock(&tid_mutex);
    if (tid != -1) {
      break; // Successfully allocated a TID
    }
  }
  printf("Thread %lu allocated TID: %dn", pthread_self(), tid);

  // Generate random sleep time between min and max sleep time from the command
  // line arguments
  int sleep_time = min_sleep + rand() % (max_sleep - min_sleep + 1);
  printf("Thread %lu sleep time: %d secondsn", pthread_self(), sleep_time);
  sleep(sleep_time);

  release_tid(tid);
  printf("Thread %lu released TID: %dn", pthread_self(), tid);

  return NULL;
}

Basically what i need is for my program to allocate all the tids at once, then start going through each thread and sleeping and releasing once it’s slept for it’s respective time. what’s happening is it’s releasing all the threads with the same sleep time, at the same time. Does anyone know how to fix this?

These are the exact instructions:

When a new thread is created, it will invoke an API call that will return a unique TID, and will call a second API call to relinquish the TID before exiting, such that the TID can be reassigned.

implementation of a multithreaded program that creates a number
of threads, where each thread will request a TID, sleep for a random period of time, and
then release the TID. Sleeping for a random period of time approximates typical TID usage
in which a TID is assigned to a new thread, the thread executes and then terminates, and
the TID is released on the thread’s termination

The
first thing that the thread function does should be to call the allocate_tid function,
whilst just before returning, or exiting, it should call the release_tid function.

after initializing the tid manager, create the number
of threads requested through the command-line flag (using pthread_create) and
subsequently wait for all the threads to finish (using pthread_join).

New contributor

lemon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật