我想试试用C#进行线程化,我知道一些关于C语言的线程.
所以我只是想问一下我是否要终止一个线程,我应该这样做,smt.Abort()
否则它会在函数结束后"自杀"?
另外,pthread_exit()
在C#中有类似C的东西 吗?
我是C语言中的多线程新手,我有这个问题.我写了以下代码:
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
pthread_mutex_t m=PTHREAD_MUTEX_INITIALIZER;
pthread_attr_t attr;
void* test(void *a)
{
int i=*((int *)a);
printf("The thread %d has started.\n",i);
pthread_mutex_lock(&m);
sleep(1);
printf("The thread %d has finished.\n",i);
pthread_mutex_unlock(&m);
pthread_exit(NULL);
}
int main()
{
int i=0;
pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_JOINABLE);
pthread_t thread[5];
for (i=0;i<5;i++)
pthread_create(&thread[i],&attr,test,&i);
for (i=0;i<5;i++)
pthread_join(thread[i],NULL);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
为什么我会得到如下值:
The thread 0 has started.
The thread 0 has started.
The thread 5 has started.
The thread 5 has started.
The thread 0 has started.
The thread 0 has …
Run Code Online (Sandbox Code Playgroud)