Cのpthread_cancel()
threa_cancel()は、スレッドIDによって特定のスレッドをキャンセルするために使用されます。この関数は、終了のために1つのキャンセル要求をスレッドに送信します。 pthread_cancel()の構文は次のようになります-
int pthread_cancel(pthread_t th);
それでは、この関数を使用してスレッドをキャンセルする方法を見てみましょう。
例
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <pthread.h>
int count = 0;
pthread_t sample_thread;
void* thread_one_func(void* p) {
while (1) {
printf("This is thread 1\n");
sleep(1); // wait for 1 seconds
count++;
if (count == 5) {
//if the counter is 5, then request to cancel thread two and exit from current thread
pthread_cancel(sample_thread);
pthread_exit(NULL);
}
}
}
void* thread_two_func(void* p) {
sample_thread = pthread_self(); //store the id of thread 2
while (1) {
printf("This is thread 2\n");
sleep(2); // wit for 2 seconds
}
}
main() {
pthread_t t1, t2;
//create two threads
pthread_create(&t1, NULL, thread_one_func, NULL);
pthread_create(&t2, NULL, thread_two_func, NULL);
//wait for completing threads
pthread_join(t1, NULL);
pthread_join(t2, NULL);
} 出力
This is thread 2 This is thread 1 This is thread 1 This is thread 2 This is thread 1 This is thread 1 This is thread 1 This is thread 2 This is thread 2 This is thread 2 This is thread 2 This is thread 2 This is thread 2 This is thread 2 This is thread 2 This is thread 2 This is thread 2 This is thread 2 This is thread 2
-
スレッドを強制終了するC#プログラム
最初にスレッドを作成して開始します- // new thread Thread thread = new Thread(c.display); thread.Start(); 次に、スレッドを表示し、停止機能を設定してスレッドの動作を停止します- public void display() { while (!flag) { Console.WriteLine("It's Working"); Thread.Sleep(2000); &nbs
-
Javaのスレッドプール
スレッドプールは、事前に初期化されたスレッドのコレクションです。スレッドプールの背後にある一般的な計画は、メソッドの起動時にさまざまなスレッドを形成し、それらが座って作業を期待する場所に配置することです。サーバーは参加の呼び出しを受信すると、このプールからスレッドを起動し(使用可能な場合)、サービスの要求を渡します。スレッドがサービスを完了すると、プールに戻り、多くの作業を待ちます。プールにアクセス可能なスレッドが含まれていない場合、サーバーはスレッドが解放されるまで待機します。 新しいスレッドを作成する必要がないため、時間を節約できます。 サーブレットとJSPで、リクエストをメソッド化す