|
|
Question : segmentation fault when pthread_mutex_lock is called
|
|
Dear Experts,
I declared a linked-list structure as shown below:
#define ... struct InputQueueNode { struct RawPktBuff *pktinfo; struct InputQueueNode *InputQueueNextPtr; pthread_mutex_t lock; };
When the program ran until the following statement,
pthread_mutex_lock(&(headPtr_Rx->lock));
a segmentation fault error message was shown.
Have i left out anything that needs to be included?
The file was compiled with:
gcc thread.c -lpthread
Please help. Thank you in advance.
|
Answer : segmentation fault when pthread_mutex_lock is called
|
|
>the thread just waits there although no thread has locked >the headPtr
But since you never initialized the lock, it may very well be locked even though no one has actively locked it. It's a roll of the dice.
>As pthread_mutex_t lock is within the queue structure, >where and how should i run pthread_mutex_init()? Everytime >a node of the queue is created? In the main function or >even before declaring the structure?
Run pthread_mutex_init() when you create the queue element. Running a subroutine is something that happens at run time, whereas declaring a structure is something that happens at compile time. So there is no such thing as running a subroutine before declaring a structure.
btw, queues have elements, not nodes. Graphs and networks have nodes. And you don't lock headPtr. You lock the queue element to which it points.
There's something basically wrong with the locking you are doing. It seems that you are locking some queue element in order to coordinate two threads' access to the queue. You need to lock the queue, not any particular queue element, to coordinate two threads' access to the queue. You need a single pthread_mutex_t lock for the queue. Hold that lock while you add something to the queue, remove something from the queue, or examine the contents of the queue.
Whether a variable is global or not is of no concern here. A global variable is one that can be accessed by a subroutine without any specific reference to it being passed to the subroutine.
What you're probably thinking of, though, is static variables. In a C program, a variable declared with the "static" attribute or declared outside of any function is a static variable. Static variables matter because unlike the more common automatic variables, you can't have two threads accessing the same static variable unless you use some locking.
|
|
|
|
|