Reputation: 23666
I would like to add a pointer (to an object) to task_struct that is shared between all threads in the group. After the object has been deleted by 1 thread, how could I ensure that another thread will not attempt to dereference the invalid pointer.
Could I add an atomic variable reference field to task_struct, and then update them in sync across all threads of a process (hold a global spinlock while traversing task_structs)?
Or implementing a kernel thread that manages the objects and their reference counts. Seems like this problem must have been solved by other shared entities like virtual memory and file handles.
Upvotes: 0
Views: 230
Reputation: 560
You could do this by defining you own datastructure: struct my_task_data { void *real_data; }
The task_struct must be enhanced: struct task_struct { .... struct my_task_data *mtd; };
In the clone() call you need to handle the mdt member of the task_struct. real_data points to whatever you want. Doing it this way means you have one pointer from each task_struct to a shared object (mtd) which is always valid and can be dereferenced at any time. This shared object contains a pointer to your actual data item. When you want to access the item do:
data = current()->mtd->real_data;
if data is NULL another thread has deleted it, otherwise it can be used.
Locking issues are not shown in this example.
Of course you need to protect access to real_data by some locking mechanism, like a mutex or semaphore in the my_task_data structure and use it while manipulating my_task_data.
Upvotes: 1