我得到每個線程壞ID,我怎麼能得到一個正確的ID?而且我必須創造一個像元帥一樣的線索,允許副駕駛,我該如何解決這個問題?我正在使用講臺作爲監視器來鎖定或解鎖允許只能訪問一個線程的互斥鎖。多線程,身份證不工作,如何添加其他功能
我有這樣的代碼:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <linux/sched.h>
typedef enum
{ false = 0, true } t_bool;
pthread_mutex_t mutex;
int rostrum;
rostrum = 0;
void *
deputy (void *arg)
{
int tid = (int *) arg;
printf ("Deputy no: %d in f() \n", tid); // ??? no.1
int SAID;
SAID = 0;
while (SAID == 0)
{
pthread_mutex_trylock (&rostrum);
if (rostrum == 0)
{
rostrum = 1;
printf ("\t Deputy no: %d is saing\n", tid);
SAID = 1;
}
pthread_mutex_unlock (&rostrum);
}
}
int
main()
{
pthread_t tid;
int i = 0;
for (i; i < 20; i++)
{
/* spurious characters deleted here */
printf ("Deputy no: %d before f().\n", i); // ??? no.2
pthread_create (&tid, NULL, deputy, &tid);
}
}
結果:
Deputy no: 0 before f()
Deputy no: 1 before f()
Deputy no: 2 before f()
Deputy no: -863940960 inf f()
Deputy no: -863940960 inf f()
Deputy no: -863940960 is saing
Deputy no: -863940960 is saing
Deputy no: 3 before f()
Deputy no: -863940960 inf f()
Deputy no: 4 before f()
Deputy no: -863940960 inf f()
Deputy no: -863940960 is saing
Deputy no: 5 before f()
Deputy no: -863940960 inf f()
Deputy no: -863940960 is saing
Deputy no: 6 before f()
Deputy no: 7 before f()
Deputy no: -863940960 inf f()
Deputy no: 8 before f()
Deputy no: -863940960 inf f()
Deputy no: -863940960 is saing
Deputy no: 9 before f()
Deputy no: 10 before f()
Deputy no: 11 before f()
Deputy no: -863940960 inf f()
Deputy no: -863940960 is saing
Deputy no: -863940960 is saing
Deputy no: -863940960 is saing
Deputy no: 12 before f()
Deputy no: -863940960 inf f()
Deputy no: -863940960 inf f()
Deputy no: -863940960 is saing
Deputy no: -863940960 inf f()
Deputy no: -863940960 inf f()
Deputy no: -863940960 is saing
Deputy no: 13 before f()
Deputy no: -863940960 is saing
Deputy no: -863940960 is saing
Deputy no: 14 before f()
Deputy no: -863940960 inf f()
Deputy no: -863940960 inf f()
Deputy no: -863940960 is saing
Deputy no: -863940960 is saing
Deputy no: 15 before f()
Deputy no: -863940960 inf f()
Deputy no: 16 before f()
Deputy no: -863940960 inf f()
Deputy no: -863940960 is saing
Deputy no: -863940960 is saing
Deputy no: -863940960 inf f()
Deputy no: 17 before f()
Deputy no: 18 before f()
Deputy no: -863940960 inf f()
Deputy no: -863940960 inf f()
Deputy no: -863940960 is saing
Deputy no: 19 before f()
Deputy no: -863940960 is saing
Deputy no: -863940960 is saing
爲什麼你將所有的線程指向一個tid var,無論如何,可能不再存在,因爲main()已經返回? –