Suppose the main thread is spawning a new thread t1, how can my code that runs on t1 find the thread id of the main thread (using c#)?
Edit:
I don\'t control the
If you are using a Threadpool (thus no control over the creation of Threads here) you could work as follows:
private static void myfunc(string arg)
{
Console.WriteLine("Thread "
+ Thread.CurrentThread.ManagedThreadId
+ " with parent " + Thread.GetData(Thread.GetNamedDataSlot("ParentThreadId")).ToString()
+ ", with argument: "
+ arg
);
}
public static int Main(string[] args)
{
var parentThreadId = System.Threading.Thread.CurrentThread.ManagedThreadId;
WaitCallback waitCallback = (object pp) =>
{
Thread.SetData(Thread.GetNamedDataSlot("ParentThreadId"), parentThreadId);
myfunc(pp.ToString());
};
ThreadPool.QueueUserWorkItem(waitCallback, "my actual thread argument");
Thread.Sleep(1000);
return 0;
}
This would produce something like:
Thread 3 with parent 1, with argument: my actual thread argument
If however there is no way to pass data to the child thread at all, consider renaming the parent thread, or alternatively all the child threads.