M
M
mIka012022-02-14 15:54:17
C++ / C#
mIka01, 2022-02-14 15:54:17

Give values ​​to the thread and return the result of execution?

Hello, this is my first time working with threads. I have a simple question, but I can't find it online.
How to pass an int[] array to a thread where some code will be executed, after execution the thread should return another array.
How to do it ?

And how, if necessary, to terminate the thread from another place, conditionally from another thread.

Thank you in advance for your response.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vasily Bannikov, 2022-02-14
@mIka01

1. First, make sure that your task really needs a thread, and not some higher-level abstraction, such as Task
2. If it is a thread, then there are two options:
1. Through a callback. At the end of your work, you need to call some method in the thread that will process the result.

using System.Threading;

var data = new int[1]; // Какие-то данные

var thread = new Thread(() => {
  var result = data.Length; // Какие-то ужасно сложные вычисления
  HandleResult(result); // Это можно передать как параметр-делегат, но тут мы будем конкретный метод использовать
});
thread.Start(); // Стартуем
// Какие-то дела
thread.Join(); // Всё равно надо по-хорошему дождаться окончания работы потока
void HandleResult(int value) {
  Console.WriteLine(value);
}

2. Through Join and some common variable or field.
using System.Threading;

var data = new int[1]; // Какие-то данные
var result = 0; // Какой-то результат (инициализируем значением по-умолчанию)
var thread = new Thread(() => {
  result = data.Length; // Какие-то ужасно сложные вычисления
});
thread.Start(); // Стартуем
// Какая-то работа
thread.Join(); // Дожидаемся окончания работы потока
Console.WriteLine(result); // Используем результат работы

T
twobomb, 2022-02-14
@twobomb

No way, just access from one thread to another directly or through Invoke. If directly and you are afraid that access can be made at the same time from two threads, use lock before writing. To cancel, implement the CancellationToken
mechanism

F
freeExec, 2022-02-14
@freeExec

You can transfer an object to a taxi. Anything can be an object. Accordingly, this will be your exchange point, you put the initial data there, and the results. Through cancellationTokenSource, you can end the task prematurely. Well, Sync is used if you have several threads and they need to synchronize with each other, or for example, you want to pick up intermediate results.

public class TaskState
    {
        public CancellationToken CancellationToken;
        public int[] Input;
        public int[] Output;
        public object Sync;
    }

    private static void TaskBodyPoolQueue(object state)
    {
            var taskState = (TaskState)state;

            do
            {
            // Calculate
            } while (!taskState.CancellationToken.IsCancellationRequested);
            taskState.Output = ...
    }

            taskStateProgress = new TaskState()
            {
                Input = ...,
                CancellationToken = cancellationTokenSource.Token,
                Sync = new object()
            };
            for (int i = 0; i < 6; i++)
                ThreadPool.QueueUserWorkItem(new WaitCallback(TaskBodyPoolQueue), taskStateProgress);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question