c - Modify PID manager for multi-threading -
below pid manager. want modify uses multi-threading. therefore each thread request pid (maybe create 20 or in while loop), sleep random period of time (i assume use sleep() ), , release pid (similar see below).
i total newbie when comes threads in c , linux if can me modify accordingly. start clone() function call?
#include <stdio.h> #include <stdlib.h> #include <limits.h> #define min_pid 300 #define max_pid 5000 #define cb char_bit int sz = max_pid - min_pid + 1; unsigned char *unsignedchar; int allocate_map(); int allocate_pid(); void release_pid(int pid); int main() { int map = allocate_map(); if (map == 1) { printf("\nbitmap data structure initialized.\n"); int id = 0, = 0; //create 20 processes while (i < 20) { int val = allocate_pid(); printf("\nprocess %d: pid = %d", i+1, val); i++; } //release few processes release_pid(303); printf("\nprocess 303 released."); release_pid(308); printf("\nprocess 308 released."); release_pid(309); printf("\nprocess 309 released."); //allocate few more processes after release int val = allocate_pid(); printf("\nprocess %d : pid = %d", ++i, val); //should 303 val = allocate_pid(); printf("\nprocess %d : pid = %d\n", ++i, val); //should 308 } else printf("\nfailed initialize data structure.\n"); } /* creates , initializes bitmap data structure representing pids; returns —1 unsuccessful, 1 successful */ int allocate_map() { unsignedchar = (unsigned char*)malloc((sz+cb-1)/cb * sizeof(char)); if (unsignedchar) return 1; return -1; } /* allocates , returns pid; returns -1 if unable allocate pid (all pids in use) */ int allocate_pid() { int = 0; int pid = unsignedchar[i/cb] & (1 << (i & (cb-1))); while (pid != 0) { i++; pid = unsignedchar[i/cb] & (1 << (i & (cb-1))); } if (i+min_pid > max_pid) return -1; unsignedchar[i/cb] |= 1 << (i & (cb-1)); return i+min_pid; } /* releases pid given pid parameter*/ void release_pid(int pid) { if (pid < 300) { printf("\ninvalid pid: should lie between 300 , 3000."); return; } int = pid - min_pid; unsignedchar[i/cb] &= ~(1 << (i & (cb-1))); }
posix threads simplest , canonical way this.
wikipedia has got nice example already.
basically, create thread instances means of pthread_create() , join them thereafter or "wait them finish" via pthread_join().
note wikipedia entry says compilation using gcc. -pthread or -lpthread strictly necessary there, otherwise you'll undefined references.
Comments
Post a Comment