当线程进入perform_work()以创建新的pid时,它会在第二次尝试执行时发出分段错误。我必须配置我的线程创建错误,但我不知道在哪里。这个问题是对Modify PID manager for multi-threading
的跟进#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <assert.h>
#define MIN_PID 300
#define MAX_PID 5000
#define CB CHAR_BIT
#define NUM_THREADS 20
int sz = MAX_PID - MIN_PID + 1;
int id;
int i;
int map;
unsigned char *unsignedChar;
int allocate_map();
int allocate_pid();
void *perform_work();
void release_pid(int pid);
int main()
{
pthread_t threads[NUM_THREADS];
int thread_args[NUM_THREADS];
int result_code, index;
//create all threads one by one
for (index = 0; index < NUM_THREADS; ++index){
thread_args[index] = index;
printf("Creating thread %d\n", index);
result_code = pthread_create(&threads[index], NULL, perform_work(), (void *) &thread_args[index]);
assert(0 == result_code);
}
// wait for each thread to complete
for (index = 0; index < NUM_THREADS; ++index) {
// block until thread 'index' completes
result_code = pthread_join(threads[index], NULL);
printf("In main: thread %d has completed\n", index);
assert(0 == result_code);
}
printf("In main: all threads completed successfully\n");
//release a few processes
release_pid(303); printf("\nProcess 303 released.");
release_pid(308); printf("\nProcess 308 released.");
release_pid(309); printf("\nProcess 309 released.");
//allocate a few more processes after this release
int val = allocate_pid(); printf("\nProcess %d : pid = %d", ++i, val); //should be 303
val = allocate_pid(); printf("\nProcess %d : pid = %d\n", ++i, val); //should be 308
}
void *perform_work(void *argument){
map = allocate_map();
i = 0;
id = 0;
if (map == 1) {
printf("\nBitmap Data Structure initialized.\n");
int val = allocate_pid();
printf("\nProcess %d: pid = %d\n", i+1, val);
i++;
}
else printf("\nFailed to initialize data structure.\n");
}
/* Creates and initializes a bitmap data structure for representing pids;
returns —1 for unsuccessful, 1 for successful */
int allocate_map() {
unsignedChar = (unsigned char*)malloc((sz+CB-1)/CB * sizeof(char));
if (unsignedChar) return 1;
return -1;
}
/* Allocates and returns a pid; returns -1
if it is unable to allocate a pid (all pids are in use) */
int allocate_pid() {
int i = 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 a pid given a pid parameter*/
void release_pid(int pid) {
if (pid < 300) {
printf("\nInvalid PID: It should lie between 300 and 3000.");
return;
}
int i = pid - MIN_PID;
unsignedChar[i/CB] &= ~(1 << (i & (CB-1)));
}